Group: comp.os.linux.networking
From: David Schwartz
Date: Saturday, March 22, 2008 9:35 AM
Subject: Re: Help: redirecting process input/output

On Mar 21, 1:06 pm, Knight wrote:

> Thank you! Last place I suspected!
> Sorry, a simple "Thank You" does not adequately express the depth of
> my gratitude for catching this bug.
>
> THANK YOU!!!! THANK YOU!!!! THANK YOU!!!! THANK YOU!!!! THANK YOU!!!!
> Vote Harris for World President!
>
> A little better.

By the way, your code is largely operating by luck. It has a very
serious, and very subtle, bug that can lead to deadlock.

You cannot assume that it is safe to refuse to read from one
connection until you finish writing to another. If two processes do
that, they can wind up each refusing to read until the other reads,
which is fatal.

You also didn't set the sockets non-blocking, which can also lead to
deadlock for much the same reason.

> if (FD_ISSET(c2p[0], &r)) {
> if ((count = read(c2p[0], buf, 1024))
>> 0) {
> write(1, buf, count);
> }
> }
> if (FD_ISSET(0, &r)) {
> if ((count = read(0, buf, 1024)) > 0)
> {
> write(p2c[1], buf, count);
> }
> }

Notice that you do not perform the second 'read' until the first
'write' completes? But your 'write' can only complete if there is
sufficient space in the pipe, which may require the consuming process
to 'read' from the pipe. But the consuming process might be blocked in
'write' waiting for space in the pipe which will only be made
available by your second 'read'. So you are each waiting for the
other.

You must not wait to call the second 'read' until the first 'write'
completes.

You can get the same deadlock the other way around as well. You could
be blocked in the first 'write', unable to find buffer space because
the program you are trying to 'write' to cannot call 'read' until you
perform the first 'read' on the next pass of your 'select' loop.

Sorry for the bad news.

The simplest fix is just to 'fork' and use one process for each
direction. Each process blocks in 'read' and then blocks in 'write'.
The way, one process blocking in 'write' won't keep the other one from
'read'ing.

Otherwise, you have to use 'select' for your writes as well, and you
must set the sockets non-blocking.

DS

Safety Articles | Usenet Groups | Usenet News | Bluegrass