#include <fcntl.h>#include <sys/stat.h>#include <semaphore.h>#include <error.h>#include <unistd.h>#include <stdlib.h>#include <stdio.h>int main()
{sem_t *s = sem_open("log", O_CREAT | O_EXCL , 0666, 0);
if(s == SEM_FAILED)
{perror("sem_open");
exit(EXIT_FAILURE);}pid_t pid;pid = fork();if(pid > 0)
{puts("parent process sleeping");
sleep(5);sem_post(s);}else if(pid == 0){puts("child process waiting");
sem_wait(s);puts("child get sem!");
}sem_unlink("log");
return 0;
}
PS:(1)posix信号量编译的时候需要额外链接库。使用-lrt 或者 –lpthread。在ubuntu 12.04 中是-lpthread,其他系统中可能是-lrt。
(2)在使用前,当前目录需存在一个log文件,可使用touch命令创建。(touch log)
(3)可在/dev/shm中查看当前系统中的posix信号量。
(4)posix有名信号量主要用于进程之间同步。而posix内存信号量(无名信号量)既可用于进程之间,也可以用于单进程下的多线程之间同步。