【问题标题】:Trying to learn how to implement Semaphores in C in a controlled loop尝试学习如何在受控循环中用 C 实现信号量
【发布时间】:2019-09-05 01:09:55
【问题描述】:

我正在尝试了解如何使用信号量。我一直在编写代码,其中一个进程在受控循环中执行多个子进程。我想实现孩子使用信号量锁访问资源。每当我写东西时,我都会遇到分段错误(核心转储)问题。每当我寻求帮助时,我都会找到一个没有很好解释的实现。这是我现在写的内容

在主程序中:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<sys/wait.h>    

#define key 0x10101010

int main(int * argc, char * argv[])
{
    int i,count=0;
    pid_t pid;
    int status;
    int *scount;
    int shmid;
    shmid = shmget(key,sizeof(int),IPC_CREAT | 0666);
    if(shmid == -1)
    {
        perror("\n SHM Error");
    }
    scount = shmat(shmid,0,0); 
    scount = 0;

    for(i = 0;i<10;i++)
    {
        pid = fork();
        if(pid < 0){
            perror("\nFork error\n");
        }
        else if(pid == 0){
            execlp("./child","./child",NULL);
            exit(0);
        }

    }
    for(i =0;i<10;i++)
    {
        if(pid > 0){
            wait(pid);
            //printf("\nI am parent and my PID %d",getppid());
        }
    }
    printf("\nTotal number of processes forked are %d\n",*scount);

sem_unlink("./semakey123");
return 0;
}


在子进程中:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<semaphore.h>

#define key 0x10101010
#define semkey 0x91919191
int main(int *argc, char *argv[])
{
    int shmid,semid;
    int *count;
    sem_t *sem;
    sem = sem_open("./semakey123",IPC_CREAT |0666);
    sem_init(sem,0,0);
    if(sem = SEM_FAILED)
     perror("\n Semaphore not opened");
    shmid = shmget(key,sizeof(int), IPC_CREAT | 0666);
    if(shmid ==-1)
    {
        perror("\n SHM Error");
    }
    else printf("\n SHM attached to CHild");
    count = shmat(shmid,0,0);
    printf("\nEntering Critical section");
    sem_wait(sem);
    sleep(3);
    *count+=1;
    printf("\n Count: %d\n",*count);
    sleep(2);
    printf("\nExiting critical section");
    sem_post(sem);
    return 0;
}

当我注释信号量相关代码时,共享内存中的 Count 超出了限制。程序在没有进入无限循环的情况下终止,但仍发生在核心转储处。在未注释信号量代码的情况下,我立即得到分段错误。任何帮助表示赞赏。

P.S:我不是编程初学者,但我是系统编程初学者。

【问题讨论】:

    标签: c linux operating-system fork semaphore


    【解决方案1】:

    我认为您一直对 System V 信号量感到困惑,因为您正在尝试使用为 System V 定义的模式设置 Posix 信号量 (http://man7.org/linux/man-pages/man3/sem_open.3.html)那些(http://man7.org/linux/man-pages/man2/semget.2.html)。 比起小心使用指针...在将共享内存映射到您的 scount 变量之后,您正在执行 scount = 0。我想您可能希望通过执行 *scount=0 将其初始化为 0。

    让我知道你是否以及如何解决 :)

    【讨论】:

    • 感谢您的回复。我一直很忙,没有检查它。我会浏览链接并回复您。
    猜你喜欢
    • 2016-09-16
    • 2014-06-28
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多