TCP servers with POSIX

The simplest form of a TCP server is one which accepts clients sequentially.

server_seq.c

Usually, server should accept multiple clients at the same time. For that purpose the function select() can be used. It traces which sockets are ready to read/write. For the server socket, ready to read means that it has new client to accept. For a client socket, that means that the request is ready to read. Such approach is called multiplexing.

server_mplex.c

Server can process multiple requests by forking process for each connected client. One server instance deals with a client until the connection is closed. Then, the process exits. Each server process is independent of the other server instances. If one of them crashes, others continue to work. The problem is large number of connected clients, which can cause server to consume lot of resources.

server_forked.c

Server can process multiple requests by creating thread for each connected client. One thread deals with a client until the connection is closed. Then, the thread is destroyed. This approach consumes less machine resources, but it is potentially less stable then the forked version.

server_threaded.c

Instead of forking process for each client at connection time, fixed number of processes can be forked at the server startup. When a client connects, the process is already forked and ready to deal with the client. Of course, number of forked processes determines maximum number of clients to connect.

server_preforked.c

Similarly, instead of creating thread for each client at connection time, fixed number of threads can be created at the server startup.

server_prethreaded.c

The two approaches of preforking/prethreading can be combined, so server forks several processes at the startup, and each of them creates fixed number of threads. Stability of independent processes is combined with efficiency of threads.

server_preforkthr.c

Multiplexing enable to accept multiple clients at once. Threading enables processing several requests at the same time. So, prethreaded server can use multiplexing to accept and process several clients at the same time. Each thread accepts multiple clients and processes requests one at the time. Thus, multiple clients are accepted and several requests are processed.

server_prethrmplex.c

Preforked prethreaded server can use multiplexing. Several processes are created within each of them several threads are created. Each thread uses multiplexing. Thus, the robustness of forked server is achieved together with ability to process several requests.

server_preforkthrmplex.c

The examples have been tested on gcc 4.3.3/Linux 2.6.29 64bit, gcc 4.2.1/FreeBSD 8.0 64bit.

ready.

10 print "mail: contact at alepho.com | skype: karastojko | stackoverflow: karastojko | github: karastojko"
20 print "(c) 2009-2023 www.alepho.com"