5

When I echo something to a named pipe made with mkfifo, it hangs if no process is reading from that pipe. How can I prevent that, i.e., stop that from hanging?

And by the way, why is that hanging echo process not listed in ps -e or pstree?

jasonwryan
  • 73,126
jojman
  • 597

1 Answers1

6

It's not totally clear what your desired end result is from the question, so I will assume that your desire is to continue the program, but still have the write occur when possible. In that case, just background the operation:

echo foo > fifo &

As for why echo is not listed in the process table, it's because echo is a shell builtin.

Chris Down
  • 125,559
  • 25
  • 270
  • 266
  • 4
    I don't think this is a reasonable answer. It will just result in a huge number of stuck echo processes lying around. (Unlike in OP's original example, they will be separate processes since they're backgrounded.) Instead some mechanism is needed to immediately produce a failure when no reader is present. – R.. GitHub STOP HELPING ICE May 12 '14 at 13:33
  • 1
    I would posit that your suggestion is far more unreasonable -- it requires storing state that never needed to be stored. The most reasonable solution entirely depends on what the expected behaviour is. – Chris Down May 12 '14 at 14:03
  • Storing state? You mean the absence/presence of a reader? That's part of the state of the fifo; any attempt to store it outside would be bogus and would be subject to race conditions. – R.. GitHub STOP HELPING ICE May 12 '14 at 14:33
  • Also, OP wants to buffer data in the pipe (until it fills up) rather than blocking when there's no reader, an easy way to achieve this is simply to have the script itself hold the fifo open for reading, but never actually read from it. (e.g. exec 3<fifo). – R.. GitHub STOP HELPING ICE May 12 '14 at 14:34
  • @R.. Is it possible to just exit from that echo and go on if nothing is reading from that pipe? Even with something like sleep, for example. – jojman May 12 '14 at 14:48
  • 1
    @Susei If that's what you want, just use timeout from GNU coreutils, or cratimeout, or SIGALRM. I would not suggest writing your own timeout logic. I would also suggest clarifying your question so your intent is more obvious to readers -- at least to me, it reads as a desire not to block rather than a desire not to write at all. – Chris Down May 12 '14 at 15:21
  • @R.. "that's part of the state of the FIFO" that is very interesting what you said. Do you think you could take a look at my question? – Braden Best Jan 24 '17 at 16:47
  • @R..GitHubSTOPHELPINGICE "OP wants to buffer data in the pipe" - It's not clear. I wouldn't say that. "easy way to achieve this is simply to have the script itself hold the fifo open for reading, but never actually read from it. (e.g. exec 3<fifo)." - bad idea - write in this case is non-blocking until the buffer is filled (typically 64k). "(until it fills up)" - and what's next? Hang? – Alek May 27 '20 at 08:18