你为什么要在Linux中关闭管道? [英] Why should you close a pipe in linux?

查看:868
本文介绍了你为什么要在Linux中关闭管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用过程进程间通信的管道,什么是封闭管的一端的目的是什么?

When using a pipe for process-process communication, what is the purpose of closing one end of the pipe?

例如:<一href=\"http://stackoverflow.com/questions/2784500/how-to-send-a-simple-string-between-two-programs-using-pipes/2784559#2784559\">How使用管道发送两个程序之间简单的字符串?

注意,管的一侧在子和父进程关闭。这是为什么需要?

Notice that one side of the pipe is closed in the child and parent processes. Why is this required?

推荐答案

如果您连接两个进程 - 父母和孩子 - 用管道,你叉之前创建管道

If you connect two processes - parent and child - using a pipe, you create the pipe before the fork.

叉使得两个进程访问该管的两端。这是不可取的。

The fork makes the both processes have access to both ends of the pipe. This is not desirable.

读出侧应该了解到,如果它注意到一个EOF条件作家已经完成。如果所有各方写作关闭这只能发生。因此,它是最好的,如果它关闭其写作FD尽快

The reading side is supposed to learn that the writer has finished if it notices an EOF condition. This can only happen if all writing sides are closed. So it is best if it closes its writing FD ASAP.

作家应该关闭它的阅读FD只是为了不有太多的文件描述符开放,从而达到开放文件描述符的可能存在的限制。此外,如果那么只有读者模具,作家得到由得到一个SIGPIPE或至少一个EPIPE错误(取决于信号是如何定义的)收到通知。如果有几个读者,作家无法检测的真正一走了,继续写作和卡作为希望的写作FD模块中,未使用的读者会读一些东西。

The writer should close its reading FD just in order not to have too many FDs open and thus reaching a maybe existing limit of open FDs. Besides, if the then only reader dies, the writer gets notified about this by getting a SIGPIPE or at least an EPIPE error (depending on how signals are defined). If there are several readers, the writer cannot detect that "the real one" went away, goes on writing and gets stuck as the writing FD blocks in the hope, the "unused" reader will read something.

所以在这里详细会发生什么:

So here in detail what happens:


  • 父进程调用管道(),并得到2文件描述符:让我们把它叫做 RD WR

  • 父进程调用叉()。现在,这两个过程有一个 RD WR

  • 假设子过程应该是读者。

  • parent process calls pipe() and gets 2 file descriptors: let's call it rd and wr.
  • parent process calls fork(). Now both processes have a rd and a wr.
  • Suppose the child process is supposed to be the reader.

然后


  • 家长应关闭其读出端(不浪费文件描述符和垂死读者正确检测)和

  • 儿童必须关闭其写入结束(为了能够检测到EOF条件)。

这篇关于你为什么要在Linux中关闭管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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