我正在尝试使用POSIX命名信号量来确保只能运行我的可执行文件的一个实例。但我遇到了麻烦;信号量的值始终为0,因此它总是阻塞。
#include <semaphore.h> /* required for semaphores */
#include <stdio.h>
#include <unistd.h> /* usleep */
#include <fcntl.h> // O_EXCL
#include <assert.h>
#include <stdlib.h> /* exit, EXIT_FAILURE */
int main(int argc, char *argv[])
{
int ret;
int i;
sem_t* semaphore;
semaphore = sem_open("/mysemaphore", O_EXCL, 0777 /*0644*/, 2);
printf("sem_open returned %p at line %u\n", semaphore, __LINE__);
// if it exists, open with "open", and parameters will be ignored (therefore given as 0)
if(!semaphore)
{
semaphore = sem_open("/mysemaphore", O_CREAT, 0, 0);
printf("sem_open returned %p at line %u\n", semaphore, __LINE__);
}
// either of the above calls should have given us a valid semaphore
assert(semaphore);
// read its value time and again
ret = sem_getvalue(semaphore, &i);
printf("sem_getvalue returned %i at line %u, value is %i\n", ret, __LINE__, i);
// ....
输出:
sem_open returned 0x8003a4e0 at line 36
sem_getvalue returned 0 at line 50, value is 0
平台:Cygwin 1.7.33-2
使用此命令构建:
gcc Main.c -o Main -lpthread
非常感谢帮助!
答案 0 :(得分:1)
使用sem_post(semaphore)
增加,sem_wait(semaphore)
减少。
此外,使用O_CREAT时,应将模式和值指定为有用的东西:
semaphore = sem_open("/mysemaphore", O_CREAT, 0777, 0);