The Linux Programming Interface

(nextflipdebug5) #1

912 Chapter 44


struct response { /* Response (server --> client) */
int seqNum; /* Start of sequence */
};
–––––––––––––––––––––––––––––––––––––––––––––––––––––– pipes/fifo_seqnum.h

Server program
Listing 44-7 is the code for the server. The server performs the following steps:

z Create the server’s well-known FIFO q and open the FIFO for reading w. The
server must be run before any clients, so that the server FIFO exists by the time
a client attempts to open it. The server’s open() blocks until the first client
opens the other end of the server FIFO for writing.
z Open the server’s FIFO once more e, this time for writing. This will never
block, since the FIFO has already been opened for reading. This second open
is a convenience to ensure that the server doesn’t see end-of-file if all clients
close the write end of the FIFO.
z Ignore the SIGPIPE signal r, so that if the server attempts to write to a client
FIFO that doesn’t have a reader, then, rather than being sent a SIGPIPE signal
(which kills a process by default), it receives an EPIPE error from the write()
system call.
z Enter a loop that reads and responds to each incoming client request t. To
send the response, the server constructs the name of the client FIFO y and
then opens that FIFO u.
z If the server encounters an error in opening the client FIFO, it abandons that
client’s request i.

This is an example of an iterative server, in which the server reads and handles each
client request before going on to handle the next client. An iterative server design
is suitable when each client request can be quickly processed and responded to, so
that other client requests are not delayed. An alternative design is a concurrent server, in
which the main server process employs a separate child process (or thread) to handle
each client request. We discuss server design further in Chapter 60.

Listing 44-7: An iterative server using FIFOs
–––––––––––––––––––––––––––––––––––––––––––––––– pipes/fifo_seqnum_server.c
#include <signal.h>
#include "fifo_seqnum.h"

int
main(int argc, char *argv[])
{
int serverFd, dummyFd, clientFd;
char clientFifo[CLIENT_FIFO_NAME_LEN];
struct request req;
struct response resp;
int seqNum = 0; /* This is our "service" */
Free download pdf