无名管道的创建函数pipe
函数原型:int pipe(int pipefd[2]);
头文件:#include <fcntl.h> #include <unistd.h>
输入参数:
pipefd: int型数组,长度为2,用于创建无名管道后存放对无名管道进行读写的文件描述符。
返回值:创建无名管道的结果,0表示成功,-1失败
函数说明
调用pipe函数创建一个无名管道,参数pipefd用于返回无名管道的文件描述符。pipefd[0] 用于存放无名管道读文件描述符,pipefd[1]用于存放无名管道的写文件描述符。向管道中写入的数据将由内核尽心缓存,直到数据从另一端被读出。
无名管道的简介与特点
- 无名管道是半双工的,在同一个进程里面,不能同时对同一个无名管道进行读写。
- 无名管道只能在有亲缘关系的进程之间使用(比如父进程与子进程)。
- 无名管道在使用时,可以被认为是一种特殊的文件,对于它的读写可以使用普通的read和write函数,但无名管道不是普通的文件,并不存在与文件系统中,只存在于内存中。
无名管道的使用
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
int main(void){
pid_t pid;
int fd[2];///write:fd[1] read:fd[0]
char buf[128];
if(pipe(fd)<0){
perror("pipe");
exit(1);
}
pid =fork();
if(pid < 0){
perror("fork");
exit(1);
}else if(pid ==0 ){
printf("child.....\n");
while(1){
bzero(buf,128);
printf("child wait input:");
fgets(buf,128,stdin);
write(fd[1],buf,strlen(buf));
}
exit(0);
}else{
printf("parent....");
while(1){
bzero(buf,128);
read(fd[0],buf,128);
printf("BUF:%s\r\n",buf);
}
exit(0);
}
return 0;
}
该程序的作用是子进程等待控制台输入,父进程从管道中读取数据,并打印到控制台。需要注意的是pipe函数的调用必须在fork函数之前,否则子进程将无法通过内存拷贝的方式获取无名管道文件描述符。