Linux无名管道pipe的使用
1.函数原型
int pipe(int pipefd[2]);
- 函数返回值:成功返回
0
;失败返回-1
;设置errorpidfd[0]
为读
;pipefd[1]
为写
- 管道中,数据读走了,就没有数据
pipe
函数包含在unistd.h
头文件中- 如果
pipe
在读数据的时候,管道中没有数据,则会保持阻塞状态,直到有数据读出
2. pipe
实例
- 使用pipe所要完成的功能为:子进程写数据到管道,父进程读数据并且将内容显示到终端实例程序:
-
#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> int main() { int pipfd[2]; char writebuf[20]="I have a dream\n"; char readbuf[20]={0}; if(pipe(pipfd)==-1) { printf("failed at create pipe\n"); } else { int forkret=fork(); if(forkret==0) { sleep(3);//用以判断当管道中没有数据,是否会阻塞 printf("Here is chailed\n"); close(pipfd[0]); write(pipfd[1],writebuf,strlen(writebuf)); // exit(0); } else if(forkret>0) { //wait(NULL); printf("Here is father\n"); close(pipfd[1]); read(pipfd[0],readbuf,1024); printf("read %s",readbuf); } else { printf("failed fork\n"); } } return 0; }
- 程序运行结果:
- 程序在运行时首先进入了父进程,当子进程还没有数据写入到管道时,子进程处于阻塞状态。