ptg10805159
Section 21.5 Source Code 815
98 if (argc != 1)
99 err_quit("usage: printd");
100 daemonize("printd");
101 sigemptyset(&sa.sa_mask);
102 sa.sa_flags=0;
103 sa.sa_handler=SIG_IGN;
104 if (sigaction(SIGPIPE, &sa, NULL) < 0)
105 log_sys("sigaction failed");
106 sigemptyset(&mask);
107 sigaddset(&mask, SIGHUP);
108 sigaddset(&mask, SIGTERM);
109 if ((err = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0)
110 log_sys("pthread_sigmask failed");
111 n=sysconf(_SC_HOST_NAME_MAX);
112 if (n < 0) /* best guess */
113 n=HOST_NAME_MAX;
114 if ((host = malloc(n)) == NULL)
115 log_sys("malloc error");
116 if (gethostname(host, n) < 0)
117 log_sys("gethostname error");
118 if ((err = getaddrlist(host, "print", &ailist)) != 0) {
119 log_quit("getaddrinfo error: %s", gai_strerror(err));
120 exit(1);
121 }
[98 – 100] The daemon doesn’t have any options (the only argument is the command
name itself ), so ifargcis not 1, we callerr_quitto print an error message
and exit. We call thedaemonizefunction from Figure13.1 to become a
daemon. After this point, we can’t print error messages to standarderror;
we need to log them instead.
[101 – 110] Wearrange to ignoreSIGPIPE.Wewill be writing to socket file descriptors,
and we don’t want a write error to triggerSIGPIPE,because the default
action is to kill the process. Next, we set the signal mask of the thread to
includeSIGHUPandSIGTERM.All threads we create will inherit this signal
mask. We’ll send theSIGHUPsignal to the daemon to tell it to reread its
configuration file.We’ll send theSIGTERMsignal to the daemon to tell it to
clean up and exit gracefully.
[111 – 117] Wecallsysconfto get the maximum size of a host name. Ifsysconffails
or the limit is undefined, we use HOST_NAME_MAX as a best guess.
Sometimes, this constant is defined for us by the platform, but if it isn’t, we
chose our own value inprint.h.Weallocate memory to hold the host
name and callgethostnameto retrieve it.
[118 – 121] Next, we try to find the network address that the daemon is supposed to use
to provide the printer spooling service.