semaphore equivalent for processes?

2019-03-06 11:24发布

问题:

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.