![](https://csdnimg.cn/release/download_crawler_static/88433997/bg4.jpg)
管道主要用于不同进程间通信。实际上,通常先创建一个管道,再通过 fork 函数创建一个
子进程。图见附件。
子进程写入和父进程读的命名管道:图见附件
管道读写注意事项:
可以通过打开两个管道来创建一个双向的管道。但需要在子理程中正确地设置文件描述符。
必须在系统调用 fork() 中调用 pipe() ,否则子进程将不会继承文件描述符。当使用半双工
管道时,任何关联的进程都必须共享一个相关的祖先进程。因为管道存在于系统内核之中,
所以任何不在创建管道的进程的祖先进程之中的进程都将无法寻址它。 而在命名管道中却不
是这样。管道实例见: pipe_rw.c
#include<unistd.h>
#include<memory.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int pipe_fd[2];
pid_t pid;
char buf_r[100];
char* p_wbuf;
int r_num;
memset(buf_r,0,sizeof(buf_r)); 数组中的数据清 0;
if(pipe(pipe_fd)<0){
printf("pipe create error\n");
return -1;
}
if((pid=fork())==0){
printf("\n");
close(pipe_fd[1]);
sleep(2);
if((r_num=read(pipe_fd[0],buf_r,100))>0){
printf("%d numbers read from be pipe is %s\n",r_num,buf_r);
}
close(pipe_fd[0]);
exit(0);
}else if(pid>0){
close(pipe_fd[0]);
if(write(pipe_fd[1],"Hello",5)!=-1)
printf("parent write success!\n");
if(write(pipe_fd[1]," Pipe",5)!=-1)
printf("parent wirte2 succes!\n");
close(pipe_fd[1]);
sleep(3);
waitpid(pid,NULL,0);