我正在尝试使用信号量编写一个小型C程序,但我遇到了这个问题,我无法解决。我总是在sem_post上遇到段错误。 以下是我的服务器代码中主要方法的相关部分:
sem_t * sem_query = NULL;
sem_t * sem_server = NULL;
sem_t * sem_client = NULL;
//prepare semaphores
init_semaphores(sem_query, sem_server, sem_client);
//prepare the shared memory
struct shm_struct * shared = init_shm();
int exit_code = 0;
while (1) {
if (sem_post(sem_query) == -1) {
perror("Error posting the semaphore!");
exit_code = 1;
break;
}
if (sem_wait(sem_server) == -1) {
if (errno == EINTR) {
printf("Received interrupting signal! Quitting now...");
break;
} else {
perror("Error while waiting on semaphore!");
exit_code = 1;
break;
}
}
//calculate the response and write it to shm
calculate_and_write_response(shared, procs);
if (sem_post(sem_client) == -1) {
perror("Error posting the semaphore!");
exit_code = 1;
break;
}
if (sem_wait(sem_server) == -1) {
if (errno == EINTR) {
printf("Received interrupting signal! Quitting now...");
break;
} else {
perror("Error while waiting on semaphore!");
exit_code = 1;
break;
}
}
}
free_shm(shared);
free_semaphores(sem_query, sem_server, sem_client);
exit(exit_code);
这是init_semaphores方法:
static void init_semaphores(sem_t * s1, sem_t * s2, sem_t * s3) {
s1 = sem_open(SEM_A_NAME, O_CREAT | O_EXCL, 0600, 0);
s2 = sem_open(SEM_B_NAME, O_CREAT | O_EXCL, 0600, 0);
s3 = sem_open(SEM_C_NAME, O_CREAT | O_EXCL, 0600, 0);
if (s1 == SEM_FAILED || s2 == SEM_FAILED || s3 == SEM_FAILED) {
perror("Could not open semaphores!");
free_semaphores(s1, s2, s3);
exit(1);
}
}
我不是在这里发布客户端线程的代码,因为它无关紧要:在启动服务器后,segfault立即发生,而客户端进程没有运行。在segfault之前没有打印出任何错误消息。
以下是gdb在运行程序时所说的内容:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff79c6b44 in sem_post@@GLIBC_2.2.5 () from /lib64/libpthread.so.0
Missing separate debuginfos, use: debuginfo-install glibc-2.17-157.el7_3.1.x86_64
因此,如果我正确读取此信息,则会在sem_post()调用中发生segfault,这必须是对sem_query的第一次调用,因为程序将在sem_wait()调用中等待。
代码有什么问题? segfault来自哪里?
答案 0 :(得分:2)
您的信号量初始化是不对的:
init_semaphores(sem_query, sem_server, sem_client);
函数init_semaphores
只会修改本地副本(s1
,s2
和s3
)。因此init_semaphores()
中的更改不会更改main()中的指针,使您的信号量设置为NULL。而是将指针传递给指针以修改它们:
//prepare semaphores
init_semaphores(&sem_query, &sem_server, &sem_client);
和
static void init_semaphores(sem_t **s1, sem_t **s2, sem_t **s3) {
*s1 = sem_open(SEM_A_NAME, O_CREAT | O_EXCL, 0600, 0);
*s2 = sem_open(SEM_B_NAME, O_CREAT | O_EXCL, 0600, 0);
*s3 = sem_open(SEM_C_NAME, O_CREAT | O_EXCL, 0600, 0);
if (*s1 == SEM_FAILED || *s2 == SEM_FAILED || *s3 == SEM_FAILED) {
perror("Could not open semaphores!");
free_semaphores(*s1, *s2, *s3);
exit(1);
}
}