Linux管道输入和输出 [英] Linux Pipes as Input and Output

查看:146
本文介绍了Linux管道输入和输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我愿做一个Linux操作系统在C程序中以下内容:

I would like to do the following inside a C program on a Linux os:


  • 创建使用系统调用管道(或2)

  • 使用EXEC执行一个新的进程()

  • 进程的标准输入连接到previously创建的管道。

  • 进程的输出连接到另一个管道。

我们的想法是,以规避性能目的的驱动器访问。

The idea is to circumvent any drive access for performance purposes.

我知道管道的建立是非常简单的管道系统调用
而且,我可以只使用popen这为输入或输出目的建立一个管道。

I know that the creation of pipes is quite simple using the PIPE system call and that I could just use popen for creating a pipe for input OR output purposes.

但你会如何去这样做的输入和输出?

But how would you go about doing this for both input and output?

推荐答案

您需要与管道相当小心:

You need to be quite careful with the plumbing:


  1. 通话管()两次,一个是管道对孩子,一个是管道,从孩子,得到4文件描述符。

  2. 调用fork()。

  3. 在小孩:

    • 调用close()标准输入(文件描述符0)。

    • 呼叫DUP() - 或dup2() - 使管道 - 子成标准输入读端

    • 调用close()上的管道对孩子的阅读结束。

    • 在管道对孩子的写入结束
    • 调用close()。

    • 调用close()在标准输出(文件描述符1)。

    • 呼叫DUP() - 或dup2() - 使管道从孩子的写入结束到标准输出

    • 对管从孩子的写入结束
    • 调用close()。

    • 调用close()上的管道 - 从孩子的阅读结束。

    • 执行所需的程序。


  • 调用close的管道对孩子的阅读结束。

  • 调用close上管从孩子的写端。

  • 循环发送对管儿童写端的数据儿童和管道 - 从孩子的读端读取从子数据

  • 在当前没有更多送孩子,管道对孩子的亲密写端。

  • 当接收到的所有数据,管道 - 从孩子的阅读关闭结束。

请注意有多少关闭有,尤其是孩子。如果你使用dup2(),您不必关闭标准输入和输出明确;但是,如果你做了明确的关闭DUP()正常工作。还要注意的是既不DUP()也不dup2()关闭该被复制的文件描述符。如果省略关闭管道,则两个程序可以正确检测EOF;事实上,目前的处理仍然可以写入一个管意味着有在管道没有EOF,和程序将无限期挂起

Note how many closes there are, especially in the child. If you use dup2(), you don't have to close standard input and output explicitly; however, dup() works correctly if you do the explicit closes. Also note that neither dup() nor dup2() closes the file descriptor that is duplicated. If you omit closing the pipes, then neither program can detect EOF correctly; the fact that the current process can still write to a pipe means that there is no EOF on the pipe, and the program will hang indefinitely.

请注意,这种解决方案并不改变为子标准误差;它去同一个地方父标准错误。通常情况下,这是正确的。如果您有从孩子的错误消息的处理方式不同的特定需求,然后采取相应的措施对孩子的标准错误了。

Note that this solution does not alter standard error for the child; it goes to the same place as standard error for the parent. Often, this is correct. If you have a specific requirement that error messages from the child are handled differently, then take appropriate action on the child's standard error too.

这篇关于Linux管道输入和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆