c - 段错误和信号量无法正常工作

标签 c segmentation-fault semaphore

我一直在为学校做这项作业,要求我编写一个程序,总共使用 3 个进程,并使用信号量从 0 计数到参数 maxnum 指定的数字,该参数必须从参数 maxnum 中初始化在两个子进程被 fork 之后,进程必须以这样的方式打印数字:主进程打印数字 0、3、6,第一个子进程打印数字 1、4、7,第二个子进程打印数字 2、5、8。我一直无法弄清楚为什么我的代码在到达代码中的第一个 sem_post() 命令时会出现段错误。我的代码在某一时刻可以工作,但是当它运行时,进程打印出数字的顺序总是完全随机的,并且永远不会接近我需要的正确顺序。我也在失败后删除了垃圾信号量,这样就消除了这个问题。对此问题的任何帮助将不胜感激。

请注意,printfs 就在那里,所以我知道它们发布的顺序,对于我的代码可能有多困惑表示抱歉。

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


#define SEM_NAME "/test.mutex"

sem_t *sem1;
sem_t *sem2;
sem_t *sem3;

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

sem1 = sem_open(SEM_NAME, O_CREAT, O_RDWR, 1);
if(sem1 == (void *)-1){
    perror("sem_open() failed ");
}
sem2 = sem_open(SEM_NAME, O_CREAT, O_RDWR, 0);
if(sem2 == (void *)-1){
    perror("sem_open() failed ");
}
sem3 = sem_open(SEM_NAME, O_CREAT, O_RDWR, 0);
if(sem3 == (void *)-1){
    perror("sem_open() failed ");
}


int *curnum;
int *maxnum;


const int segment_size = 4096;


int segment_id = shmget(IPC_PRIVATE, segment_size,S_IRUSR|S_IWUSR);


curnum = (int *) shmat(segment_id, NULL, 0);
maxnum = curnum + 1;


if(fork()){
    if(fork()){
        *maxnum = atoi(argv[1]);
        sem_wait(sem1);
        while(*curnum <= *maxnum){
            printf("%d", *curnum);
            printf(" Main \n");
            ++curnum[0];
            sem_post(sem2);
            sem_wait(sem1);
        }
        printf("Exiting Main Loop");
        sem_post(sem2);
        wait();
        shmctl(segment_id, IPC_RMID, NULL);
    }
    else{
        sem_wait(sem3);
        while(*curnum <= *maxnum){
            printf("%d", *curnum);
            printf(" Child 1\n");
            ++curnum[0];
            sem_post(sem1);
            sem_wait(sem3);
        }
        printf("Exiting Child 1 Loop");
        sem_post(sem1);
    }
}
else{
    sem_wait(sem2);
    while(*curnum <= *maxnum){
        printf("%d", *curnum);
        printf(" Child 2\n");
        ++curnum[0];
        sem_post(sem3);
        sem_wait(sem2);
    }
    printf("Exiting Child 2 Loop");
    sem_post(sem3);
}

sem_close(sem1);
sem_close(sem2);
sem_close(sem3);

sem_unlink(SEM_NAME);


/* remove shared memory segment */
//shmctl(segment_id, IPC_RMID, NULL);

return 0;
}

最佳答案

我刚刚修复了我的程序,使其正常工作,我创建了另外两个 SEM_NAME 定义并使用它们来存储 sem2 和 sem3。我将 while 循环更改为 while 循环,并删除了大部分 sem_post 调用,现在它可以正常工作了。

关于c - 段错误和信号量无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29471649/

相关文章:

c - C 中的基本文件 IO

linux - sem_post() 因有效信号量而失败

c# - Task.WhenAll() 一次只执行 2 个线程?

c++ - 在 C(也是 C++)中, '&' 运算符如何同时用作地址运算符和按位运算符?由于 C 不支持运算符重载

C 使用odbc将图像插入ms sql数据库

c - 如何创建一个修改结构体的函数

c++ - 段错误,无法找到任何指针为 NULL 的位置

c - 使用递归函数反向打印链表

c - 从 64 位机器中的 C 函数访问返回地址时出现段错误

c - 在 Linux 下使用信号量和共享内存