semaphore equivalent for processes?

*爱你&永不变心* 提交于 2019-12-02 15:14:16

问题


I have a parent process that forks two children. I need to force a certain order for when these child processes run.

For example, the parent process takes a "command" from a file, and depending on that command, the parent will either pass that command to child a or child b using unnamed pipes. I need stuff to happen in the children in the same order that the parent received the command from the file.

The way I was using semaphores did not work between processes. Any ideas?


回答1:


Semaphores work just fine between processes. For example:

#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>

int main(void)
{
  // Error checking omitted for expository purposes
  sem_t *sem = sem_open("test_semaphore", O_CREAT|O_EXCL, 0, 1);
  sem_unlink("test_semaphore");
  int child = fork();
  printf("pid %d about to wait\n", getpid());
  sem_wait(sem);
  printf("pid %d done waiting\n", getpid());
  sleep(1);
  printf("pid %d done sleeping\n", getpid());
  sem_post(sem);

  if(child > 0)
  {
    int status;
    printf("parent done, waiting for child\n");
    wait(&status);
  }

  printf("pid %d exiting\n", getpid());
  return 0;
}

Output:

$ time ./a.out
pid 61414 about to wait
pid 61414 done waiting
pid 61415 about to wait
pid 61414 done sleeping
parent done, waiting for child
pid 61415 done waiting
pid 61415 done sleeping
pid 61415 exiting
pid 61414 exiting

real    0m2.005s
user    0m0.001s
sys 0m0.003s



回答2:


If you use IPC semaphores they also work for forks. Look here: http://www.advancedlinuxprogramming.com/alp-folder Chapter 5 will give you the informations you need.



来源:https://stackoverflow.com/questions/6659780/semaphore-equivalent-for-processes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!