我有以下问题。我想确保信号量被正确初始化,所以我把if放在那里,当发生错误时应该是真的。
if ((sem_t *semaphore = sem_open("/sem1", O_CREAT | O_EXCL, 0644, 1))
== SEM_FAILED) {handle error}
看起来,如果出现错误,它运行得很好——我可以处理这个错误。但当那个条件为false时,那个么并没有创建信号量,我意识到了这一点,因为进程在sem_wait(信号量(上停止。当我运行不带"if"的代码时,它运行得很好,但我无法检测到任何错误。
我该怎么办?
看起来像是在if
语句的内部声明(另一个?(semaphore
变量。我假设这是编译的,并且您已经在其他地方声明了semaphore
。
简短回答:从if
语句中删除sem_t *
。
不能在if
-语句中定义变量。
试试这个:
sem_t * semaphore = NULL;
if (SEM_FAILED == (semaphore = sem_open("/sem1", O_CREAT | O_EXCL, 0644, 1)))
{
perror("sem_open() failed");
/* handle error */
}
甚至更清晰:
sem_t * semaphore = sem_open("/sem1", O_CREAT | O_EXCL, 0644, 1);
if (SEM_FAILED == semaphore)
{
perror("sem_open() failed");
/* handle error */
}