Linux pipe函数

pipe


头文件

#include <unistd.h>

函数原型

int pipe(int pipefd[2]);

#define _GNU_SOURCE       
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);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值