Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

unix - Setting up pipelines reading from named pipes without blocking in bash

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.

To demonstrate:

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.pipe opens in RW mode (as opposed to opening in read-only mode as with 5</tmp/foobar.pipe) although O_NONBLOCK is still set. Thanks to waldner on irc://irc.freenode.org/#bash for this pointer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...