0

你知道为什么这段 C 代码以“分段错误”结尾吗?

#include <semaphore.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>


#define NAMESEM "/mysem"

int main(int argc, char* argv) {
 sem_t* sem;
 int fd = shm_open(NAMESEM, O_RDWR|O_CREAT|O_EXCL|O_TRUNC, 0);

 ftruncate(fd, sizeof(sem_t));

 sem = mmap(NULL, sizeof(sem_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

 sem_init(sem, 1, 0);

 sem_wait(sem);

 return 0;
}

我已经关注了此处找到的所有关于此的帖子,但似乎 sem_init() 会产生分段错误,我不知道为什么。我在指针上犯了一些错误吗?

4

1 回答 1

5

Consider the flags passed to shm_open in this line:

int fd = shm_open(NAMESEM, O_RDWR|O_CREAT|O_EXCL|O_TRUNC, 0);
                                  ^^^^^^^^^^^^^^

This means it will work the first time, when NAMESEM doesn't exist. Subsequent shm_opens will fail because of O_EXCL. Which in turn means ftruncate and mmap will fail. The gist of the issue is that these IPC objects survive after the program dies, until explicitly removed or until the system is restarted.

O_EXCL

If O_CREAT was also specified, and a shared memory object with the given name already exists, return an error.

But really the true problem in your code is that you're not checking the return values for these functions. A simple perror would immediately point out the problems.

于 2013-02-03T13:53:38.180 回答