sem_wait的Coredump

use*_*533 1 c linux synchronization ipc fedora

我在这里有一个相当奇怪的问题,或者我不知道它的工作方式,但是无论如何,我下面的程序都会以适当的方式正确创建信号量并首次运行到结尾。但是,如果信号灯已存在,则SEGFaults在sem_wait上。我在64位Fedora 17上运行此程序。这是否与错误有关?

#include <stdio.h>          /* printf()                 */
#include <stdlib.h>         /* exit(), malloc(), free() */
#include <sys/types.h>      /* key_t, sem_t, pid_t      */
#include <sys/shm.h>        /* shmat(), IPC_RMID        */
#include <errno.h>          /* errno, ECHILD            */
#include <semaphore.h>      /* sem_open(), sem_destroy(), sem_wait().. */
#include <fcntl.h>          /* O_CREAT, O_EXEC          */

int
main() {


        sem_t *mysem;
        int oflag = O_CREAT | O_EXCL;
        mode_t mode = 0777;
        const char semname[] = "mysem";
        unsigned int value = 1;
        int sts;


        mysem = sem_open(semname, oflag, mode, value);
        //sem_unlink(semname);

        if(mysem == (void *)-1) {
                printf("sem_open() failed");
                exit(1);
        }

        printf("opened a semaphore successful\n");

        if(!sem_wait(mysem)) {
                /*locked */
                printf("worked\n");
        } else {
                printf("error\n");
        }
         return 0;
}
Run Code Online (Sandbox Code Playgroud)

/ dev / shm sem.mysem的内容

Program received signal SIGSEGV, Segmentation fault.
0x000000332980d5f0 in sem_wait () from /lib64/libpthread.so.0
Missing separate debuginfos, use: debuginfo-install glibc-2.15-58.fc17.x86_64
(gdb) where
#0  0x000000332980d5f0 in sem_wait () from /lib64/libpthread.so.0
#1  0x000000000040074a in main () at str2.c:31
Run Code Online (Sandbox Code Playgroud)

奇怪的问题是,当我删除/ dev / shm中的信号量或取消注释sem_unlink时,它每次都有效。我在这里做错了吗,还是需要在某个地方运行sem_post?

谢谢。

Som*_*ude 5

如果sem_open失败,则返回SEM_FAILED,这在我的系统(可能还有其他所有人)上等同于NULL。而不是进行检查-1

另外,如果失败,则打印实际错误(使用例如perror()strerror())。