[lug] named pipe missunderstanding

Chris McDermott csmcdermott at gmail.com
Wed Feb 2 20:32:21 MST 2011

My guess is that the problem is happening because both functions close the
pipe when they're done with their operation.  My experience with pipes has
always been smoother if I had the first process open the pipe for reading
and then keep it open more or less permanently, while the other process
periodically writes to it.

This: http://www.linuxjournal.com/article/2156 has always been my go-to
article for named pipes.  Money quotes:

If you watch closely, you'll notice that the first command you run appears
> to hang. This happens because the other end of the pipe is not yet
> connected, and so the kernel suspends the first process until the second
> process opens the pipe. In Unix jargon, the process is said to be “blocked”,
> since it is waiting for something to happen.

Create two named pipes, pipe1 and pipe2. Run the commands:
> echo -n x | cat - pipe1 > pipe2 &
> cat <pipe2 > pipe1
> On screen, it will not appear that anything is happening, but if you run *
> top* (a command similar to *ps* for showing process status), you'll see
> that both *cat* programs are running like crazy copying the letter *x*back and forth in an endless loop.
> After you press ctrl-C to get out of the loop, you may receive the message
> “*broken pipe*”. This error occurs when a process writing to a pipe when
> the process reading the pipe closes its end. Since the reader is gone, the
> data has no place to go. Normally, the writer will finish writing its data
> and close the pipe. At this point, the reader sees the *EOF* (end of file)
> and executes the request.
> Whether or not the “broken pipe” message is issued depends on events at the
> exact instant the ctrl-C is pressed. If the second *cat* has just read the
> *x*, pressing ctrl-C stops the second *cat*, *pipe1* is closed and the
> first *cat* stops quietly, i.e., without a message. On the other hand, if
> the second *cat* is waiting for the first to write the *x*, ctrl-C causes
> *pipe2* to close before the first *cat* can write to it, and the error
> message is issued. *This sort of random behavior is known as a “race
> condition”*.

So my bet is that sometimes, the second routine is closing the named pipe
while the first is still writing to it, or about to write to it, or
something along those lines.  Maybe that's what Anthony was trying to say
earlier, not sure.  Anyway, is there a specific reason you need to close the
fis after it reads something?  Why not just leave it open for reading?
Maybe that's a java thing I'm missing, but while (true) is gonna stay
running anyway...

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20110202/20d68084/attachment.html>

More information about the LUG mailing list