int pipe(int pipefd[2]);
pipefd[0] : 表示读管道 pipefd[1] : 表示写管道 返回 0表示成功,非零表示建立失败。linux
代码事例数组
//匿名管道 int main() { int fds[2]; int len; char buf[100]={}; if(pipe(fds)==-1) //建立管道 perror("pipe"),exit(1); while(fgets(buf,100,stdin)) { len = strlen(buf); if(write(fds[1],buf,len)==-1) //把内容写进管道 perror("write"),exit(1); memset(buf,0x00,sizeof(char)*100); if(read(fds[0],buf,len)==-1) //从管道里面读取内容到数组中 perror("read"),exit(1); if(write(1,buf,len)==-1) //把从管道里读出的内容写到标准输出 perror("write"),exit(1); } return 0; }
结果展现微信
平常运用事例 who | wc -l
这样的事例咱们常常用到,用管道链接命令会令你驾轻就熟。函数
图片解析spa
####利用管道进行父子进程通讯命令行
图片解析原理 代码示例:3d
//父子进程通讯 int main() { char buf[1024]="change world!\n"; int fds[2]; if(pipe(fds)==-1) perror("pipe"),exit(1); pid_t pid = fork(); //建立匿名管道 if(pid==0) { close(fds[0]); //关闭管道读描述符 if(write(fds[1],buf,1024)==-1) //写进管道 perror("write"),exit(1); close(fds[1]); exit(1); } else { memset(buf,0x00,1024); close(fds[1]); //关闭管道写描述符 if(read(fds[0],buf,1024)==-1) //从管道读内容 perror("read"),exit(1); if(write(1,buf,1024)==-1) perror("write"),exit(1); close(fds[0]); exit(1); } return 0; }
结果 详细过程图解
code
####管道读写规则blog
当没有数据可读时生命周期
当管道满的时候
咱们刚刚能够用匿名管道在父子进程之间通讯,那若是是两个不想光的进程之间该如何通讯呢?
在命令行能够直接建立mkfifo filename
也能够在程序内部建立,相关函数
int mkfifo(const char *pathname, mode_t mode);
代码示例:
int main() { mkfifo("my.p",0644); return 0; }
####无关进程之间通讯代码示例
从标准输入读入内容进管道
#include<string.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main() { mkfifo("my.p",0664); int outfd = open("my.p",O_WRONLY); if(outfd==-1) perror("open my.txt"),exit(1); char buf[1024]={}; int n = 0; while(fgets(buf,1024,stdin)) { write(outfd,buf,1024); memset(buf,0x00,1024); } close(outfd);
从管道中读内容,标准输出输出
#include<string.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main() { int infd = open("my.p",O_RDONLY); if(infd==-1) perror("open my.p"),exit(1); char buf[1024]={}; int n = 0; while((n = read(infd,buf,1024))>0) { write(1,buf,n); memset(buf,0x00,1024); } close(infd); unlink("my.p"); //删除管道 return 0; }
运行结果: 这里就利用管道实现了两个无关进程之间的通讯。
###匿名管道和命名管道的区别。
精选文章都同步在公众号里面,公众号看起会更方便,随时随地想看就看。微信搜索 龙跃十二 或者扫码便可订阅。
<p align="center"><image src="https://tva1.sinaimg.cn/large/006tNbRwly1galsp9a07kj30p00dwae3.jpg" ></image></p>