Linux管道pipe使用实例

函数

#include <unistd.h>

int pipe(int filedes[2]);

描述

pipe()函数创建一个管道和指向该管道的一对文件描述符,并且将文件描述符存储到文件描述符数组filedes[]中。其中filedes[0]为读端,filedes[1]为写端。

 

返回值

0 – 管道创建成功;

-1 – 管道创建失败,同时errno置位;

错误指示

EFAULT – 无效的输入参数filedes;

EMFILE – 达到当前进程允许的文件描述符最大值;

ENFILE – 达到系统允许的打开文件的最大数;

实例

下边的例子首先创建一个管道,然后通过fork()创建当先进程的子进程。接着每个进程关闭读写管道不需要的文件描述符。子进程在当前路径下执行“ls –a”命令,通过将管道写描述符fd[1]复制成标准输出,将命令执行输出写到管道;父进程通过fd[0]读取管道数据并显示。


#include <sys/wait.h>#include <assert.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>int main(int argc, char *argv[]){    int fd[2];

	pid_t pid;

	char read_buffer[500] = {0};

	int read_count = 0;

	int status = 0;

	//创建管道

	if (pipe(fd) < 0)

	{

		printf("Create pipe failed.");

		return -1;

	}

	//创建子进程

	if ((pid = fork()) < 0)

	{

		printf("Fork failed.");

		return -1;

	}

	//子进程操作

	if (pid == 0)

	{

		printf("[child]Close read endpoint...");

		close(fd[0]);   /* 关闭不使用的读 文件描述符 */

		//复制fd[1]到标准输出

		if (fd[1] != STDOUT_FILENO)

		{

			if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)

			{

				return -1;

			}

			//close fd[1],标准输出即为fd[1]

			close(fd[1]);

		}

		//执行命令

		status = system("ls –a");

		if (status == -1)

		{

			return -1;

		}

	}

	else

	{

		printf("[parent]Close write endpoint...");

		//父进程 读 操作

		close(fd[1]);   /* 关闭不使用的写 文件描述符 */

		//从管道读数据

		read_count = read(fd[0], read_buffer, 500);

		printf("Content under current directory: \n%s", read_buffer);

	}

}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值