Example: Using 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 the spawn() API to create children jobs to handle the incoming connection. The child process inherits the following attributes with the spawn() API:

  • The socket and file descriptors.
  • The signal mask.
  • The signal action vector.
  • The environment variables.

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 contains links to usage notes on specific APIs. If you need more details about 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() API call:

  1. The socket() API returns a socket descriptor, which represents an endpoint. The statement also identifies that the INET (Internet Protocol) address family with the TCP transport (SOCK_STREAM) is used for this socket.
  2. After the socket descriptor is created, the bind() API gets a unique name for the socket.
  3. The listen() allows the server to accept incoming client connections.
  4. The server uses the accept() API to accept an incoming connection request. The accept() call blocks indefinitely, waiting for the incoming connection to arrive.
  5. The spawn() API 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() API 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 API calls:

  1. After the spawn() API is called on the server, the recv() API receives the data from the incoming connection.
  2. The send() API echoes data back to the client.
  3. The close() API ends the spawned worker job.