【发布时间】:2017-03-23 21:01:49
【问题描述】:
我正在使用 中包含的信号量在 C 中编写一小段代码,但我无法继续,因为在 sem_getvalue 行上我总是遇到分段错误。有人可以解释我为什么吗?谢谢
编辑:我用 gcc -lpthread -lrt -l c 编译
#include <semaphore.h>
#include <stdlib.h>
#define N 3
#define FILENAME "resource.txt"
#define SEM_PROC "/semname"
int main(){
FILE* f = fopen(FILENAME, "w");
sem_t* proc_semaphore = sem_open(SEM_PROC, O_CREAT, "0777", 0);
if (proc_semaphore == SEM_FAILED) {
printf("[FATAL ERROR] Could not open the named semaphore\n");
exit(1);
}
printf("Sem created\n");
int* current= malloc(sizeof(int)); *current = -N;
sem_getvalue(proc_semaphore, current);
printf("current value: %d\n:", *current);
【问题讨论】:
-
不要转换 malloc 的结果
-
"0777"肯定是错误的(删除引号),但这不应该导致崩溃。而且您没有包含 stdlib.h,如果您没有转换 malloc 的结果(不要转换 malloc 的结果),编译器会抱怨它,但如果这将是一个问题,它应该有导致*current = -N行崩溃,而不是sem_getvalue。而且您没有检查sem_open是否成功。这可能是最重要的错误。 -
好的,谢谢,我意识到错误出现在 sem_open 函数中。但是现在我不明白为什么 sem_open 总是失败。
-
(我也不明白你为什么不直接使用
int current = -3; sem_getvalue(proc_semaphore, &current);) -
当 sem_open 失败时,您是否打印出
strerror(errno)?当系统调用失败时,您应该始终这样做。
标签: c process synchronization semaphore