c - 为什么会出现段错误(C 中的信号量)?

标签 c get segmentation-fault semaphore

#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdlib.h>
#include <errno.h>

#define SEM_KEY_FILE ("idSem.txt")

//sem_open
int main (int argc, char *argv[]) {

int sem_fd;
key_t sem_key;
int sem_id;
sem_fd = open(SEM_KEY_FILE, O_RDWR);
if (sem_fd < 0) {
    perror("Nepodarilo sa otvorit kluc pre citanie");
    return 1;
}
if (read(sem_fd, &sem_key, sizeof(key_t)) != sizeof(key_t)) {
    perror("Chyba pri citani kluca semafora");
    return 2;
}
close(sem_fd);
sem_id = semget((key_t)sem_key, 0, 0666);
printf("%d\n", sem_id);
if (sem_id < 0)
{
    perror("Sada s takymto klucom neexistuje");
    return 3;
}
printf("%d\n", (int) sem_key);
return 0;
}

我在其他 c 文件 sem_create 中创建并初始化信号量。有一个 sem_key 被写入 idSem.txt 在这个文件 sem_open 我想从文本文件中获取 sem_key 并检查信号量是否存在,但我只得到段错误,因为 sem_id 是 -1。我做错了什么吗?

#include <stdio.h>
#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/sem.h>
#include <stdlib.h>
#include <time.h>


union semun{
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminfo *__buf;
};

//sem_create
int main (int argc, char *argv[]) {

int hodnota = atoi(argv[1]);
int id;
srand((unsigned)time(NULL));
int kluc;

union semun sem_union;
sem_union.val = hodnota;

do{
kluc = rand() % 100000;
id = semget((key_t)kluc, 1, 0666 | IPC_CREAT | IPC_EXCL);
}while (id == -1);

if (semctl(id, 0, SETVAL, sem_union) == -1)
    {
    perror("Neuspesne nastavenie hodnoty");
    exit(1);
    return 1;
    }
printf("%d\n", id);
return 0;   
}

最佳答案

由于文件只是普通的 ascii 文本,这一行需要一些额外的代码:

if (read(sem_fd, &sem_key, sizeof(key_t)) != sizeof(key_t)) {

类似于:

char asciiSemKey[20];
if (read(sem_fd, asciiSemKey, sizeof(asciiSemKey)) < 1)) {
  /* Do your error stuff here. */
}
...
sem_key = atol(asciiSemKey);

关于c - 为什么会出现段错误(C 中的信号量)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185205/

相关文章:

ios - 在二进制数据中查找字符串

c - 分别通过 TCP 套接字发送和接收字符串

c - 为什么它不违反分段?

c++ - 我不断在链接列表上收到段错误

Python & clang : try. .. except 语句不适用于段错误(核心转储)

用 C 实现的干净、独立的 VM,编译代码大小在 100-200K 以内?

get - flutter/Dart : get and set with private variables

asp-classic - 没有多线程的 ASP 经典 GET 请求

python - 在 python 中对 HTTPS(证书错误)进行 GET 和 PUT 操作

c - 插入二叉树时出现段错误