lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On Mar 5, 2007, at 9:38 AM, gary ng wrote:


--- Gé Weijers <ge@weijers.org> wrote:
Using dup2 would give you two read/write file
descriptors. If you  
close one nothing happens, because the Unix kernel
waits until the  
last once is closed before doing anything. Closing
stdout/fd 1 in a  
inetd client will not magically do a 'shutdown' on
the sending side  
of a TCP connection. Bernstein's problem still
exists.
But if I instead do a shutdown(), the receiving
end(i.e. the one I fork() with a dup2 stdin/out, both
use the same underlying socket), it would solve the
problem ? As it seems that shutdown a socket would
make all fds that relies on it signal EOF ?


A TCP stream contains 2 logically separate streams, one going out and once coming in. Shutdown allows you to end the conversation on one of them, but keep the connection open in the other direction. If you do a fd:shutdown("send") the other side of the connection gets a 0 byte read. fd:read will still work until the other side does a shutdown or close.

So if you send some information you'd get code like:

fd:write(data)
fd:shutdown("send")
....
fd:read()

This will allow you to read incoming data after you have sent all there is to send.

Doing a 'dup2' creates another file descriptor, but this descriptor does not differ in any way from the original one. The underlying software (e.g. the network stack or file system) will only be notified of a 'close' when all file descriptors pointing to the same file/socket have been closed. So 'shutdown' is still necessary.

Daniel Bernstein's observation was that if the socket interfaces would have returned 2 file descriptors instead of one 'close' could have done the job, and software could have been oblivious of the differences between pipes, files and sockets. He's not alone in thinking that. See Rob Pike's presentation: http://herpolhode.com/rob/ugly.pdf.

I'm not so sure than porting the BSD socket interface to all kinds of other OSes and languages was such a good idea.



--
Gé Weijers