我正在做作业,这是轨道:
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/