管道
一种文件,因此可以使用IO函数对管道读写
- 特点1:数据单向流动
- 特点2:仅能用于父子进程/兄弟进程间的通信
使用管道可以来连接一个进程的输出和另一个进程的输入
管道的工作原理:管道是内核中的一个单项的数据通道。管道有一个读取端和写入端。
管道有缺陷:效率不高,是一个队列,导致缓冲大小受限,如果出现多个进程读取数据必然会出现数据读取不完整(Unix/Linux编程实践教程P321)
1. 创建管道
#include <unistd.h>
result = pipe(int array[2]);
array[0]:读取端文件描述符 array[1]:写入端文件描述符
return 0->success -1 -> error
2. 使用管道
-
Weird Demo – 同一进程间的管道
/** * * Demostrates: how to create and use a pipe * * Effect: create a pipe, <process perspective> write into writing end, then runs around and reading from * reading end. A litte weird, but demostrates the idea. * * result = pipe(int array[2]); * array[0]:读取端文件描述符 array[1]:写入端文件描述符 */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> int main() { int aPipe[2]; char buf[BUFSIZ]; int result; // create a pipe if(result = pipe(aPipe)){ perror("Create pipe fail.\n"); exit(1); } printf("Create pipe sucessfully! It's file descriptor: {%d, %d}\n", aPipe[0], aPipe[1]); // illustrate // read from stdin, write into pipe, read from pipe, and print on screen(stdout) // https://s3.ax1x.com/2020/12/19/rNXBHs.png this pic shows how data transports while(fgets(buf, BUFSIZ, stdin)){ int len = strlen(buf); // write buf into pipe if( write(aPipe[1], buf, len) != len){ perror("write into pipe"); break; } // read data from pipe len = read(aPipe[0], buf, len); if(len == -1){ perror("reading from pipe"); break; } // print on screen (write data into stdout) if(write(STDOUT_FILENO, buf, len) != len){ perror("writing to stdout"); break; } } }
-
使用pipe & fork在两个进程间共享管道
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main()
{
int aPipe[2];
char buf[BUFSIZ];
if(pipe(aPipe) ==</