我正在尝试掌握信号量。我编写了一个处理信号量的程序,其中我有这个函数来创建单个信号量:
int semcreate()
{
semp = semget(ftok("./output.txt", 'a'),1,IPC_CREAT|IPC_EXCL|0664);
if(semp == -1) /*Semaphore exists, fetch*/
{
printf("Semaphore fetched\n");
semp = semget(ftok("./output.txt", 'a'), 1, 0);
}
else if(semp>=0) /*Semaphore created here*/
{
printf("Semaphore created\n");
seminit(); /* Initialize semaphore*/
}
return 1;
}
当我从两个单独的终端运行该程序时,两个实例都会打印Semaphore fetched
。这是正确的行为吗?为什么?
最佳答案
系统上可能存在该信号量。使用命令ipcs
列出系统中的所有信号量,并使用ipcrm
删除您的程序创建的信号量。
关于c - 为什么信号量被获取而不被创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15881064/