管道是Unix IPC中两个进程进行通讯的最基本机制。
通常,管道由一个 进程创建,管道用于父进程和子进程间的通讯,一个进程内的管道是没有意义的,管道是半双工的,数据只流向一个方向。
pipe()参数返回两个文件标示符, pipefd[0] 打开供读数据, pipfd[1] 为pipefd[0] 写入数据
filedes[0]用于读出数据,读取时必须关闭写入端,即close(filedes[1]);
filedes[1]用于写入数据,写入时必须关闭读取端,即close(filedes[0])。
pipefd表示管道,数据写进pipefd[1] (如同STDOUT), 然后从pipefd[0] 读出(如同STDIN)
数据只能由一个进程流向另一个进程(其中一个读管道,一个写管道);如果要进行双工通信,需要建立两个管道。
管道只能用于父子进程或者兄弟进程间通信,也就是说管道只能用于具有亲缘关系的进程间通信。
必须在fork()中调用pipe(),否则子进程不会继承文件描述符。两个进程不共享祖先进程,就不能使用pipe。但是可以使用命名管道。
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
int main()
{
int fd[2];
pid_t pid;
char string[]="hello my pipe!";
char readbuffer[100];
int result=pipe(fd);
if(result==-1)
{
printf("fail to create pipe\n");
return -1;
}
pid=fork();
if(pid==-1)
{
printf("fail to fork\n");
return -1;
}
if(pid==0)
{//child process
printf("this is child process\n");
close(fd[0]);//close read,before write
result=write(fd[1],string,strlen(string));
return 0;
}else
{//parent process
printf("this is parent process\n");
close(fd[1]);
read(fd[0],readbuffer,sizeof(readbuffer));
printf("parent read from child: %s\n",readbuffer);
}
}
运行结果: