【发布时间】:2013-12-10 06:12:45
【问题描述】:
我在这里有一个相当奇怪的问题,或者我不知道它的工作方式,但是我有下面的程序可以正确创建信号量并第一次运行到最后。但是如果信号量已经存在,SEGFaults at 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;
}
/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
奇怪的问题是,当我删除 /dev/shm 中的信号量或取消注释 sem_unlink 时,它每次都有效。我在这里做错了什么还是需要在某个地方运行 sem_post?
谢谢。
【问题讨论】:
标签: c linux synchronization ipc fedora