views:

3480

answers:

6

In socket programming, you create a listening socket and then for each client that connects, you get a normal stream socket that you can use to handle the client's request. The OS manages the queue of incoming connections behind the scenes.

Two processes cannot bind to the same port at the same time - by default, anyway.

I'm wondering if there's a way (on any well-known OS, especially Windows) to launch multiple instances of a process, such that they all bind to the socket, and so they effectively share the queue. Each process instance could then be single threaded; it would just block when accepting a new connection. When a client connected, one of the idle process instances would accept that client.

This would allow each process to have a very simple, single-threaded implementation, sharing nothing unless through explicit shared memory, and the user would be able to adjust the processing bandwidth by starting more instances.

Does such a feature exist?

Edit: For those asking "Why not use threads?" Obviously threads are an option. But with multiple threads in a single process, all objects are shareable and great care has to be taken to ensure that objects are either not shared, or are only visible to one thread at a time, or are absolutely immutable, and most popular languages and runtimes lack built-in support for managing this complexity.

By starting a handful of identical worker processes, you would get a concurrent system in which the default is no sharing, making it much easier to build a correct and scalable implementation.

+15  A: 

You can share a socket between two (or more) processes in Linux and even Windows.

Under Linux (Or POSIX type OS), using fork() will cause the forked child to have copies of all the parent's file descriptors. Any that it does not close will continue to be shared, and (for example with a TCP listening socket) can be used to accept() new sockets for clients. This is how many servers, including Apache in most cases, work.

On Windows the same thing is basically true, except there is no fork() system call so the parent process will need to use CreateProcess or something to create a child process (which can of course use the same executable) and needs to pass it an inheritable handle.

Making a listening socket an inheritable handle is not a completely trivial activity but not too tricky either. DuplicateHandle() needs to be used to create a duplicate handle (still in the parent process however), which will have the inheritable flag set on it. Then you can give that handle in the STARTUPINFO structure to the child process in CreateProcess as a STDIN, OUT or ERR handle (assuming you didn't want to use it for anything else).

EDIT:

Reading the MDSN library , it appears that WSADuplicateSocket is a more robust or correct mechanism of doing this; it is still nontrivial because the parent/child processes need to work out which handle needs to be duplicated by some IPC mechanism (although this could be as simple as a file in the filesystem)

CLARIFICATION:

In answer to the OP's original question, no, multiple processes cannot bind(); just the original parent process would call bind(), listen() etc, the child processes would just process requests by accept(), send(), recv() etc.

MarkR
Multiple processes can bind by specifying the SocketOptionName.ReuseAddress socket option.
sipwiz
But what's the point? Processes are more heavyweight than threads anyway.
Anton Tykhyy
Excellent, nice and simple. I didn't think of inheritable handles. Will try it and report back!
Daniel Earwicker
Looking very good, the child processes service the single queue of incoming connections as expected. I'll update my question with a link to a blog post when I get some time.
Daniel Earwicker
Processes are more heavyweight than threads, but as they only share things explicitly shared, less synchronisation is required which makes programming easier and could even be more efficient in some cases.
MarkR
Moreover, if a child process crashes or breaks in some way, it is less likely to affect the parent.
MarkR
A: 

It sounds like what you want is one process listening on for new clients and then hand off the connection once you get a connection. To do that across threads is easy and in .Net you even have the BeginAccept etc. methods to take care of a lot of the plumbing for you. To hand off the connections across process boundaries would be complicated and would not have any performance advantages.

Alternatively you can have multiple processes bound and listening on the same socket.

TcpListener tcpServer = new TcpListener(IPAddress.Loopback, 10090);
tcpServer.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
tcpServer.Start();

while (true)
{
    TcpClient client = tcpServer.AcceptTcpClient();
    Console.WriteLine("TCP client accepted from " + client.Client.RemoteEndPoint + ".");
}

If you fire up two processes each executing the above code it will work and the first process seems to get all the connections. If the first process is killed the second one then gets the connections. With socket sharing like that I'm not sure exactly how Windows decides which process gets new connections although the quick test does point to the oldest process getting them first. As to whether it shares if the first process is busy or anything like that I don't know.

sipwiz
+1  A: 

Another approach (that avoids many complex details) in Windows if you are using HTTP, is to use HTTP.SYS. This allows multiple processes to listen to different URLs on the same port. On Server 2003/2008/Vista/7 this is how IIS works, so you can share ports with it. (On XP SP2 HTTP.SYS is supported, but IIS5.1 does not use it.)

Other high level APIs (including WCF) make use of HTTP.SYS.

Richard
+1  A: 

Have a single task whose sole job is to listen for incoming connections. When a connection is received, it accepts the connection - this creates a separate socket descriptor. The accepted socket is passed to one of your available worker tasks, and the main task goes back to listening.

s = socket();
bind(s);
listen(s);
while (1) {
  s2 = accept(s);
  send_to_worker(s2);
}
HUAGHAGUAH
How is the socket passed to a worker? Bear in mind that the idea is that a worker is a separate process.
Daniel Earwicker
fork() perhaps, or one of the other ideas above.Or maybe you completely separate the socket I/O from data processing; send the payload to worker processes via an IPC mechanism. OpenSSH and other OpenBSD tools use this methodology (without threads).
HUAGHAGUAH
+1  A: 

Under Windows (and Linux) it is possible for one process to open a socket and then pass that socket to another process such that that second process can also then use that socket (and pass it on in turn, should it wish to do so).

The crucial function call is WSADuplicateSocket().

This populates a structure with information about an existing socket. This structure then, via an IPC mechanism of your choice, is passed to another existing process (note I say existing - when you call WSADuplicateSocket(), you must indicate the target process which will receive the emitted information).

The receiving process can then call WSASocket(), passing in this structure of information, and receive a handle to the underlying socket.

Both processes now hold a handle to the same underlying socket.

Blank Xavier
+2  A: 

I would like to add that the sockets can be shared on Unix/Linux via AF__UNIX sockets (inter-process sockets). What seems to happen is a new socket descriptor is created that is somewhat of an alias to the original one. This new socket descriptor is sent via the AFUNIX socket to the other process. This is especially useful in cases where a process cannot fork() to share it's file descriptors. For example, when using libraries that prevent against this due to threading issues. You should create a Unix domain socket and use libancillary to send over the descriptor.

See:

For creating AF_UNIX Sockets:

For example code:

zachthehack