
int pipe(int pipefd[2]); pipefd[0] : 表示读管道 pipefd[1] : 表示写管道 返回 0 表示成功,非零表示创建失败。
代码事例
//匿名管道 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 这样的事例我们经常用到,用管道连接命令会令你得心应手。
图片解析
####利用管道进行父子进程通信 图片解析原理 代码示例:
//父子进程通信 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; } 结果 详细过程图解
####管道读写规则
当没有数据可读时
当管道满的时候
我们刚刚可以用匿名管道在父子进程之间通信,那如果是两个不想光的进程之间该如何通信呢?
在命令行可以直接创建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; } 运行结果: 这里就利用管道实现了两个无关进程之间的通信。
###匿名管道和命名管道的区别。