Monday, August 29, 2011

Duplicating a Socket


Duplicating a UNIX / Linux Socket 

Earlier we have seen a how to associate a socket with a stream and Using separate read and write streams on a socket. In the previous post (using separate read and write stream on a socket) I have shown the dup function. To understand why Listing 10.2 works, the dup(2) function will be reviewed here in case some readers are unfamiliar with its use:

#include <unistd.h>
int dup(int oldfd);

UNIX systems, like Linux, allow multiple file descriptors to refer to the same open file (or, in this case, a socket). By calling dup(2) with the socket s as an input argument, you are returned a new file descriptor. This new descriptor also refers to the original socket s. After this duplication has been performed, however, the socket itself will be shut down by the kernel only when the last of these two file descriptors are closed (assuming shutdown(2) is not used). Numbers always help to clarify an example. Assume that, in Listing 10.2, socket s is created on file descriptor 3. Assume also that the socket s is duplicated as follows:

int s2;      /* dup'ed socket */
s2 = dup(s); /* duplicate */

If file descriptor 4 is not currently in use, the Linux kernel will return 4 in the example shown. This allows the file descriptor 3 (variable s) and the file descriptor 4 (variable s2) to both refer to the same socket.


Now we have seen how we can duplicate the socket. Now it is time to see how we can close the dual streams. Follow this link.

1 comment:

  1. This alone necessitates that I development my MUD on Linux and not Windows.

    ReplyDelete