POSIX semaphore 发表于 2020-02-02 更新于 2023-02-26 无名信号量 除非使用共享内存,否则只能控制通同一进程的线程 1234// 初始化信号量sem的初始值为valueint sem_init (sem_t *__sem, int __pshared, unsigned int __value)// 删除信号量int sem_destroy (sem_t *__sem) 有名信号量1234567891011// name是名称// oflag:O_CREAT:如果信号量不存在则新建,存在直接返回// 如果为O_CREAT|O_EXCL,则已存在的话会返回错误// mode:// value:初始值sem_t *sem_open(const char *name, int oflag);sem_t *sem_open(const char *name, int oflag, mode_t mode, unsigned int value);// 关闭进程内信号量int sem_close (sem_t *__sem)// 从内核中删除有名信号量int sem_unlink (const char *__name) 示例 12345678910111213141516171819202122232425262728293031int pid = fork();if (pid<0) { cout << "fork failed";}if (pid==0) { sem_t* sem=sem_open("test", O_CREAT, 0666, 1); int rs = sem_wait(sem); if (rs<0) { cout << "wait failed"; exit(-1); } else { cout << "success 1" << endl; sleep(3); sem_post(sem); sem_close(sem); }} else { sem_t* sem=sem_open("test", O_CREAT, 0666, 1); int rs=sem_wait(sem); if (rs<0) { cout << "wait failed"; exit(-1); } else { cout << "success 2" << endl; sleep(3); sem_post(sem); sem_close(sem); } int tmp; wait(&tmp);} 共用操作1234567891011121314151617// 阻塞获取,值-1int sem_wait (sem_t *__sem)// 阻塞超时获取int sem_timedwait (sem_t *__restrict __sem, const struct timespec *__restrict __abstime)struct timespec { __time_t tv_sec; // Seconds __syscall_slong_t tv_nsec; // Nanoseconds};// 非阻塞获取信号量,成功放回0,值-1;失败返回-1// EINTR:信号处理函数中断调用// EINVAL:信号量sem值无效// EAGAIN:信号量不足int sem_trywait (sem_t *__sem)// 释放信号量,值+1int sem_post (sem_t *__sem)// 获取当前信号量的值,存在svalint sem_getvalue (sem_t *__restrict __sem, int *__restrict __sval) 参考文献 Linux Programmer’s Manual Linux信号量