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 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.
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:
- 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.
- After the socket descriptor is created, the bind() function
gets a unique name for the socket.
- The listen() allows the server to accept incoming
client connections.
- The server uses the accept() function to accept an
incoming connection request. The accept() call block indefinitely
waiting for the incoming connection to arrive.
- 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.
- 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:
- After the spawn() function is called on the server,
the recv() function receives the data from the incoming
connection.
- The send() function echoes data back to the client.
- The close() function ends the spawned worker job.