Search code examples
javaprocessserversocket

In Java, how do I write a socket server that spawns a NEW PROCESS to handle a request?


I was NOT asking how to handle the requests in a newly-created thread. I was asking about how to do that in a newly-created process, although I know its downside.

To fork a process to handle the request, the server socket somehow needs to pass the client socket object to the child process. How does that get passed? Is it by serializing it and passing it as one of the arguments of Runtime.exec()?

Also, from the TCP connection point of view, I could imagine that a new TCP connection is created between the client process and the spawned process. So how is this created? Is this transparent to the client? Does the client know that a new process is spawned to handle it?


Solution

  • What you want to do is not possible with plain Java:

    You cannot "serialize" a client socket and pass it anywhere: The Socket class is not the "real" socket of the operating system, it is only a Java-side "control object" holding some Java-internal information and the ID of the operating system socket. This ID - depending on the operating system - just an integer file handle. This handle cannot be transferred between existing processes1. When creating a new process (note the little 'p') on some operating systems, notably the Unix derived ones, all open file handles are duplicated from the parent to the child (the new process). This includes the socket handles. Then a child could handle the request. But that mechanism is not supported by all operating systems. Java decided to support only that stuff that is available on all supported operating systems. This means that a new Process implicitly closes almost all file handles including the socket stuff. Bad luck.

    Also you cannot create a new TCP connection to the client in a transparent way. A new TCP connection is a new TCP connection - it requires cooperation on both sides of the connection. This is the opposite of "transparent".


    1At least not in Java. With plain C and on Linux you could use special system calls to do so.