我想使用POSIX命名信号来确保我的可执行程序只有一个实例可以运行。但我遇到了麻烦;信号量的值始终为0,因此它总是阻塞。命名为POSIX信号量的问题
#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值是否有任何地方的任何代码,实际上增加(调用sem_post( ))在你的信号量? – nos