pipe
头文件
#include <unistd.h>
函数原型
int pipe(int pipefd[2]);
#define _GNU_SOURCE
int pipe2(int pipefd[2], int flags);
int pipe2(int pipefd[2], int flags);
参数
参数pipefd返回两个文件描述符:pipefd[0]为读而打开,pipefd[1]写而打开。其中pipefd[1]的输出就是pipifd[0]的输入。
功能
调用pipe可以建立管道,并将文件描述词由参数pipefd数组返回。成功返回0,否则返回1,错误原因存于errno中。
单个进程中的管道几乎没有任何用处。一般来说调用pipe的进程会接着调用fork,这样就有了父进程到子进程(或反向)的半双工管道,可以告别只通过fork或exec实现父、子进程间的通信。而且,在此之后父进程可以关闭pipefd[1],子进程关闭pipefd[0]从而构建从子进程到父进程的通道。
例子
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int filedes[2];
char buffer[80];
pipe(filedes);
if(fork() > 0)
{
char s[] = "hello!\n";
write(filedes[1], s, sizeof(s));
}
else
{
read(filedes[0], buffer, 80);
printf("%s", buffer);
}
}
unix环境高级编程的例子
#include <unistd.h>
#include <stdio.h>
int main(void)
{
int n;
int fd[2];
pid_t pid;
char line[100];
if(pipe(fd) < 0)
{
printf("pipe error");
exit(1);
}
if((pid = fork()) < 0)
{
printf("fork error\n");
exit(1);
}
else if(pid > 0)
{
close(fd[0]);
write(fd[1], "hello world\n", 12);
}
else
{
close(fd[1]);
n = read(fd[0], line, 100);
write(STDOUT_FILENO, line, n);
}
exit(0);
}