Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 13.7 Client–Server Model 479


sigaddset(&sa.sa_mask, SIGTERM);
sa.sa_flags = 0;
if (sigaction(SIGHUP, &sa, NULL) < 0) {
syslog(LOG_ERR, "can’t catch SIGHUP: %s", strerror(errno));
exit(1);
}
/*
*Proceed with the rest of the daemon.
*/
/* ... */
exit(0);
}

Figure 13.8 Alternative implementation of daemon rereading configuration files

After initializing the daemon, we install signal handlers forSIGHUPandSIGTERM.We
can either place the reread logic in the signal handler or just set a flag in the handler and
have the main thread of the daemon do all the work instead.

13.7 Client–ServerModel


Acommon use for a daemon process is as a server process. Indeed, in Figure13.2, we
can call thesyslogdprocess a server that has messages sent to it by user processes
(clients) using a UNIX domain datagram socket.
In general, aserveris a process that waits for aclientto contact it, requesting some
type of service. In Figure13.2, the service being provided by thesyslogdserver is the
logging of an error message.
In Figure13.2, the communication between the client and the server is one way.
The client sends its service request to the server; the server sends nothing back to the
client. In the upcoming chapters, we’ll see numerous examples of two-way
communication between a client and a server—the client sends a request to the server,
and the server sends a reply back to the client.
It is common to find servers thatforkandexecanother program to provide
service to a client. These servers often manage multiple file descriptors: communication
endpoints, configuration files, log files, and the like. At best, it would be careless to
leave these file descriptors open in the child process, because they probably won’t be
used in the program executed by the child, especially if the program is unrelated to the
server.Atworst, leaving them open could pose a security problem — the program
executed could do something malicious, such as change the server’s configuration file
or trick the client into thinking it is communicating with the server,thereby gaining
access to unauthorized information.
An easy solution to this problem is to set the close-on-exec flag for all file
descriptors that the executed program won’t need. Figure13.9 shows a function that we
can use in a server process to do just this.
Free download pdf