Семафоры прекрасно работают между процессами. Например:
#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;
}
Выход:
$ 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