操作系统,分支,共享内存和信号量

时间:2013-07-23 17:12:46

标签: c fork shared-memory semaphore pid

我正在做作业,这就是赛道:

  

命令行给出2个数字:argv [1] =子数(n),argv [0] =变量(m)   父亲生成n个儿子并创建共享内存段。然后等到儿子们结束工作。

     

儿子使用信号量修改必须写入并更新到共享内存中的变量m。

     

当儿子结束时,父亲打印出变量m中包含的值。

这是新代码:

[CODE]

#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;
}

[/ CODE]

你怎么看?提前谢谢你

2 个答案:

答案 0 :(得分: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` */

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

答案 1 :(得分:0)

This This将帮助您使用信号量和共享内存

相关问题