2013-07-23 37 views
0

我正在做的家庭作业,这是轨道:手术系统,叉,共享内存和信号灯

命令行得到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]

你觉得呢?预先感谢您

+0

的argv [0]将给出可执行文件的文件名! – sujin

回答

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` */ 

您需要的信号,以防止共享内存同时访问。

+0

谢谢,那么[CODE] m =(* int)共享内存; [/ CODE]是我需要将变量m放入共享内存的代码?如何将信号放入shared_memory内? – user2611556

+0

@ user2611556你可以使用'sem_open'创建一个指定的信号量,然后它将被共享。 –

+0

我们在课上没有学习sem_open。我只能使用像我上面写的功能.. – user2611556