Example: Use the spawn() API to create child processes

This example shows how a server program can use the spawn() API to create a child process that inherits the socket descriptor from the parent.

The server job waits for an incoming connection, and then calls spawn() to create children jobs to handle the incoming connection. The child process inherits the following attributes with the spawn() function:

The following figure illustrates how the server, worker, and client jobs interact when the spawn() server design is used.


Server, worker, and client job interaction when the spawn() server design is used.

Flow of socket events: Server that uses spawn() to accept and process requests

The following sequence of the socket calls provides a description of the graphic. It also describes the relationship between the server and worker examples. Each set of flows contain links to usage notes on specific APIs. If you need more details on the use of a particular API, you can use these links. The first example uses the following socket calls to create a child process with the spawn() function call:

  1. The socket() function returns a socket descriptor representing an endpoint. The statement also identifies that the INET (Internet Protocol) address family with the TCP transport (SOCK_STREAM) being used for this socket.
  2. After the socket descriptor is created, the bind() function gets a unique name for the socket.
  3. The listen() allows the server to accept incoming client connections.
  4. The server uses the accept() function to accept an incoming connection request. The accept() call block indefinitely waiting for the incoming connection to arrive.
  5. The spawn() function initializes the parameters for a work job to handle incoming requests. In this example, the socket descriptor for the new connection is mapped over to descriptor 0 in the child program.
  6. In this example, the first close() function closes the listening socket descriptor. The second close () call ends the accepted socket.

Socket flow of events: Worker job created by spawn()

The second example uses the following sequence of function calls:

  1. After the spawn() function is called on the server, the recv() function receives the data from the incoming connection.
  2. The send() function echoes data back to the client.
  3. The close() function ends the spawned worker job.
Related information
spawn()
bind()
socket()
listen()
accept()
close()
send()
recv()