1、父子进程通过共享内存进行数据通信。父子进程通过竞争方式来创建一个共享内存单元,然后子进程接受用户输入的信息,并将其写入到共享内存单元;父进程则从共享内存单元将该信息读出。 code: root@ubuntu:/code/chap9# cat test4.c #include<errno.h> #include<fcntl.h> #include<stdio.h> #include<string.h> #include<unistd.h> #include<sys/shm.h> #include<sys/stat.h> #include<sys/wait.h> #include<stdlib.h> int main(int argc,char * argv[]) { int pid; pid = fork(); if(pid==-1){ perror("fork"); exit(EXIT_FAILURE); } else if(pid==0) { //child int id=shmget((key_t)12345,50*sizeof(char),IPC_CREAT); // 创建共享内存 if(id==-1){ perror("fork"); exit(EXIT_FAILURE); } char * ptr=(char*)shmat(id,NULL,0); //映射共享内存 if(ptr==NULL){ int ret=shmctl(id,IPC_RMID,NULL); if(ret==-1){ perror("remove"); exit(EXIT_FAILURE); } } int i; for(i=0;argv[1][i]!='/0';i++) //写入内容 *ptr=argv[1][i]; ptr++; } printf("this is child.wri