进程间通信----pipe方式
流程:1.fork创建子进程
2.pipe创建管道
3.子进程:关闭写, sleep(2)后,开始read ,关闭读。
4.父进程:关闭读,开始write, waitpid,关闭写。
#include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h>
main(void) { int fd[2]; pid_t child; char s[] = "pipe is good!"; char buf[20]; if (pipe(fd) < 0) { printf("create pipe error:%s\n",strerror(errno)); exit(1); } if((child = fork()) < 0) { printf("fork error:%s\n",strerror(errno)); exit(1); } if(0 == child) { close(fd[1]); //close another one
sleep(2); // must have this
printf("child read...\n"); if(read(fd[0],buf,sizeof(s)) < 0) { printf("read error:%s\n", strerror(errno)); exit(1); } printf("\nread:%s\n", buf); close(fd[0]); //remember to close
// exit(0); // no needed
} else { close(fd[0]); printf("father process:write...\n"); if(write(fd[1],s,sizeof(s)) < 0) { printf("write error:%s\n", strerror(errno)); exit(1); } printf("write ok!\n"); close(fd[1]); waitpid(child, NULL, 0); // must have! compare difference form without
// exit(0); // why need this?
} }
|
最重要两点: sleep 和 waitpid 使得两进程同步!
阅读(1580) | 评论(0) | 转发(0) |