我想使用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