Forking and multithreading

Another possible solution to multiplexing socket connections is to start a new thread or process for each connection. In this case, blocking sockets are fine, as they block only their servicing thread/process, and they do not block other threads/processes. This can be a useful technique, but it also has some downsides. First of all, threading is tricky to get right. This is especially true if the connections must share any state between them. It is also less portable as each operating system provides a different API for these features.

On Unix-based systems, such as Linux and macOS, starting a new process is very easy. We simply use the fork() function. The fork() function splits the executing program into two separate processes. A multi-process TCP server may accept connections like this:

while(1) {
socket_client = accept(socket_listen, &new_client, &new_client_length);
int pid = fork();
if (pid == 0) { //child process
close(socket_listen);
recv(socket_client, ...);
send(socket_client, ...);
close(socket_client);
exit(0);
}
//parent process
close(socket_client);
}

In this example, the program blocks on accept(). When a new connection is established, the program calls fork() to split into two processes. The child process, where pid == 0, only services this one connection. Therefore, the child process can use recv() freely without worrying about blocking. The parent process simply calls close() on the new connection and returns to listening for more connections with accept().

Using multiple processes/threads is much more complicated on Windows. Windows provides CreateProcess(), CreateThread(), and many other functions for these features. However—and I can say this objectively—they are all much harder to use than Unix's fork().

Debugging these multi-process/thread programs can be much more difficult compared to the single process case. Communicating between sockets and managing shared state is also much more burdensome. For these reasons, we will avoid fork() and other multi-process/thread techniques for the rest of this book.

That being said, an example TCP server using fork is included in this chapter's code. It's named tcp_serve_toupper_fork.c. It does not run on Windows, but it should compile and run cleanly on Linux and macOS. I would suggest finishing the rest of this chapter before looking at it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.47.59