打开一个信号量 return 0

Opening a semaphore return 0

char* cath="/cath";
char* cathFlag="/cathf";
char* hyp="/hyp";
char* hypFlag="/hypf";

printf("SEMS OPEN\n");
sem_t *csem = sem_open(cath, O_CREAT, 0777, 0);
printf("CSEM: %d\n", *csem);
perror("ERROR: ");
sem_t *cfsem = sem_open(cathFlag, O_CREAT, 0777, 0);
sem_t *hsem = sem_open(hyp, O_CREAT, 0777, 0);
sem_t *hfsem = sem_open(hypFlag, O_CREAT, 0777, 0); 
printf("SEMS OPENED\n");

sem_open returns 0, perror写Success,信号量不打开。查看 sem_overview 后,我发现问题可能出在开头没有斜杠的名称中,添加没有帮助。无法访问信号量,当 sem_post 被调用时 shell 中止进程并出现分段错误。帮助我了解问题所在。 编辑:如果我重新启动系统(并清理信号量?),perror returns“没有这样的文件或目录”,但是在returns“成功”之后。

这是我尝试过的并且有效的方法:

#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */
#include <semaphore.h>
#include <stdio.h>


int main(void)
{

char* cath="/cath";
char* cathFlag="/cathf";
char* hyp="/hyp";
char* hypFlag="/hypf";

printf("SEMS OPEN\n");
sem_t *csem = sem_open(cath, O_CREAT, 0777, 0);
//perror("ERROR: ");
sem_t *cfsem = sem_open(cathFlag, O_CREAT, 0777, 0);
sem_t *hsem = sem_open(hyp, O_CREAT, 0777, 0);
sem_t *hfsem = sem_open(hypFlag, O_CREAT, 0777, 0); 
printf("SEMS OPENED\n");

}

我编译的:

$ gcc tsem.c -l pthread

我运行它:

$ ./a.out
SEMS OPEN
SEMS OPENED

我看了/dev/shm:

$ ls /dev/shm
sem.cath  sem.cathf  sem.hyp  sem.hypf