c - 操作系统、fork、共享内存和信号量

标签 c fork shared-memory semaphore pid

我正在做作业,这是轨道:

The command line give 2 numbers: argv[1] = number of sons (n), argv[0] = variable (m) the father generates n sons and create the shared memory segment. then wait until the sons end their job.

The sons work with a semaphore to modify the variable m that must be written and updated into the shared memory.

When the sons end, the father prints out the value contained in the variable m.

这是新代码:

[代码]

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

struct shared {  // shared structure
   sem_t sem;
   int m;
};

void error(char *msg) {  // debug function
    pritnf("%s error.\n");
    return 1;
}

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

    int sid;    // segment id
    struct shared *data;    
    pid_t pid;

    if(argc<3) error("argc");

    if(argv[1]<0) error("argv");

    if(sid = shmget(IPC_PRIVATE, sizeof(shared *data),0666)<0) error("sid-shmget"); // father create sid

    if(data = (struct shared*) shmat(sid,(void *)0,1)<0) error("data-shmat"); // father allocate structure into his address scope

    data.m = argv[2]; // father initialize m

    if(sem_init(&data.sem)<0) error("sem_init"); // father initialize semaphore

    for (int i=0; i<atoi(argv[1]);i++) {  // create sons
        if((pid = fork())<0) error("fork");
    }

    if (pid>0) {  // father
        wait(NULL);  // wait for sons
        sem_wait(&data.sem);  // entry section
        printf("valore: %d\n", data.m);
        sem_post(&data.sem);  // exit section

    } else {  // son
        if(data = (struct shared*) shmat(sid,(void *)0,1)<0) error("shmat"); // son allocate data into his address scope

        sem_wait(data.sem); // entry section

                if (data.m%2 != 0) data.m*=2;  // modify variable
        else data.m-=1;

                sem_post(&data.m);  // exit section
        }

    shmdt(&data); // father and sons deallocate data

    if (pid>0) {  // father delete semaphore and sid
        sem_delete(&data.sem);
        shmctl(sid,IPC_RMID,0);
    }

return 0;
}

[/代码]

你觉得怎么样?预先感谢您

最佳答案

您必须将共享变量放置在共享内存中。一种方法是让它成为指向共享内存中某处的指针:

int *m;

/* ... */

/* In the first process... */
m = (int *) shared_memory;
*m = 5;  /* Initialize `m` to the value `5` */

/* In the second process... */
m = (int *) shared_memory;
*m += 10;  /* Add `10` to the shared variable `m` */

/* Back in the first process */
printf("%d\n", *m);  /* Will print `15` */

您需要信号量来防止同时访问共享内存。

关于c - 操作系统、fork、共享内存和信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17816731/

相关文章:

c - stdout 重定向更改输出

c - 如何测试调用进程是否是fork

c - 首次输出到 stdout 后特定子进程的用户 CPU 时间

c - Linux - 如何在 C 中更改 fork 进程的信息

python - 从 numpy memmap 切片创建 ndarray

c - 在 C 中创建动态矩阵的方法?

c - 在 C 中切换 unsigned int 的给定范围的位

git - 将 Github 分支添加到现有存储库

c++ - 为什么我可以使用 POSIX 创建一个比安装在/dev/shm 上的大小更大的共享内存?

python - 在 celery 任务中共享巨大的分类器对象