设置从命名管道读取的管道而不会在 bash 中阻塞

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/179291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:30:11  来源:igfitidea点击:

Setting up pipelines reading from named pipes without blocking in bash

bashunixshellpipe

提问by Charles Duffy

I'm looking to call a subprocess with a file descriptor opened to a given pipe such that the open() call does not hang waiting for the other side of the pipe to receive a connection.

我正在寻找一个子进程,它的文件描述符打开给给定的管道,这样 open() 调用就不会挂起,等待管道的另一端接收连接。

To demonstrate:

展示:

$ mkfifo /tmp/foobar.pipe
$ some_program --command-fd=5 5</tmp/foobar.pipe

In this case, some_programis not run until some process has /tmp/foobar.pipeopen for write; however, some_programhas useful effects even when it isn't receiving commands, so desired behavior is for some_programto be immediately executed.

在这种情况下,some_program直到某个进程/tmp/foobar.pipe打开写入时才运行;然而,some_program即使在它没有接收命令时也有有用的效果,因此需要some_program立即执行所需的行为。

Mechanisms to do this by exec'ing through an alternate scripting language (python, perl, etc) or a C wrapper which open /tmp/foobar.pipewith the O_NONBLOCKflag are obvious; I'm looking for a pure-bash solution, should one be possible.

通过替代脚本语言(python、perl 等)或/tmp/foobar.pipeO_NONBLOCK标志打开的 C 包装器来执行此操作的机制是显而易见的;我正在寻找一种纯 bash 解决方案,如果可能的话。

回答by Charles Duffy

Opening the FD read/write rather than read-only when setting up the pipeline prevents blocking.

在设置管道时打开 FD 读/写而不是只读可以防止阻塞。

To be a bit more specific:

更具体一点:

$ mkfifo /tmp/foobar.pipe
$ some_program --command-fd=5 5<>/tmp/foobar.pipe

prevents the undesired blocking behavior, as 5<>/tmp/foobar.pipeopens in RW mode (as opposed to opening in read-only mode as with 5</tmp/foobar.pipe) although O_NONBLOCKis still set. Thanks to waldner on irc://irc.freenode.org/#bash for this pointer.

防止不希望的阻塞行为,因为5<>/tmp/foobar.pipe在 RW 模式下打开(而不是在只读模式下打开5</tmp/foobar.pipe),尽管O_NONBLOCK仍然设置。感谢 irc://irc.freenode.org/#bash 上的 waldner 提供了这个指针。

回答by Sec

The only way I know getting this kind of result is a hack:

我知道获得这种结果的唯一方法是 hack:

mkfifo /tmp/foobar.in
mkfifo /tmp/foobar.out
( cat </tmp/foobar.in ) >/tmp/foobar.out &
some_program --command-fd=5 5</tmp/foobar.out

perhaps this helps :-)

也许这有帮助:-)