sem_init何时导致段错误?

时间:2016-02-19 21:03:54

标签: c segmentation-fault semaphore

我正在试图弄清楚为什么我对sem_init的初始化信号量的调用导致我的程序出现段错误。

GDB告诉我:

Program received signal SIGSEGV, Segmentation fault.
0xb7fb142e in sem_init@@GLIBC_2.1 () from /usr/lib/libpthread.so.0
(gdb) backtrace
#0  0xb7fb142e in sem_init@@GLIBC_2.1 () from /usr/lib/libpthread.so.0
#1  0x080492ce in main (argc=3, argv=0xbffff9e4) at server.c:284

当我尝试评论该行时,程序运行正常。这是违法的代码:

我将我的信号量放在带有其他一些int变量

的结构中
    struct stats {

    ...
    /* Semaphore should be put in the struct because when the process forks the
     * child will get a copy of the semaphore. Therefore it won't function as
     * intended. By putting it in the struct, it is located on the in the shared
     * mem
     */
    sem_t *sem;
};

然后我尝试在这里实际使用它

int shmid;
struct stats *statsPtr;

//Create or get the shared mem
if ((shmid = shmget(IPC_PRIVATE, sizeof(struct stats), READ_WRITE_MODE)) < 0) {
    perror("shmget");
    exit(1);
}

//Attach the shared mem to process
if((statsPtr = shmat(shmid, 0, 0)) == (void *) -1){
    perror("shmat");
    exit(1);
}
//Init the semaphore
if((sem_init((statsPtr->sem), 0, 1))  < 0) {
  perror("semaphore init problem");
  exit(1);
  }

我环顾四周,似乎找不到可能造成这种情况的好答案。我发现了这个问题here,问题是他们没有分配他们刚刚声明指针的内存,但我认为我有一个不同的问题,因为我相信我在这里分配内存:

//Create or get the shared mem
if ((shmid = shmget(IPC_PRIVATE, sizeof(struct stats), READ_WRITE_MODE)) < 0) {
    perror("shmget");
    exit(1);
}

我也不认为我之前的函数调用失败,因为它们都包含在if语句中。有没有人建议我可以尝试解决这个问题/知道为什么会发生这种情况?

0 个答案:

没有答案