使用pipe()实现父子进程间通信,要求父进程作为写端,子进程作为读端。
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <unistd.h>
5 #include <sys/types.h> //pid_t
6 #include <sys/wait.h>
7 int main()
8 {
9 int fd[2]; //定义文件描述符数组 fd[0]读 fd[1]写
10 int ret=pipe(fd); //创建管道
11 if(ret==-1)
12 {
13 perror(“pipe”);
14 exit(1);
15 }
16 pid_t pid=fork(); //创建子进程
17 if(pid>0) //父进程
18 {
19 //父进程—写
20 close(fd[0]); //关闭读端
21 char *p=“hello,pipe\n”;
22 write(fd[1],p,strlen§+1); //写数据
23 close(fd[1]);
24 wait(NULL);
25 }
26 else if(pid==0)
27 {
28 //子进程—读
29 close(fd[1]); //关闭写端
30 char buf[64]={0};
31 ret=read(fd[0],buf,sizeof(buf)); //读数据
32 close(fd[0]);
33 write(STDOUT_FILENO,buf,ret); //将读到的数据写到标准输出
34 }
35 return 0;
36 }