【发布时间】:2020-09-06 14:27:15
【问题描述】:
进程 1 派生出进程 2 和 3,每个进程将一个与其编号相等的字符写入共享内存。最后一个进程应该读取内存
输出应该看起来像“读取:123”,但我得到“读取:1”(只有最后一个进程号)
我不知道如何在多个进程中使用共享内存,有什么帮助吗?
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <zconf.h>
#include <sys/sem.h>
#include <wait.h>
int main(){
int pid1, pid2, pid3, semid, shmid, n=3;
semid = semget(1, 1, 0);
shmid = shmget(2,1024,0666|IPC_CREAT);
char *number = (char *) shmat(shmid, (void *) 0, 0);
pid1=getpid();
pid2=fork();
pid3=fork();
if(pid3==0) {
printf("Process 3 is writing...\n");
gets(number);
}
else if(pid2==0){
wait(NULL);
printf("Process 2 is writing...\n");
gets(number);
}
else{
wait(NULL);
printf("Process 1 is writing...\n");
gets(number);
printf("read: %s\n", number);
}
}
我只是想得到一些关于多进程内存写入的建议。
【问题讨论】: