ptg10805159
Section 21.5 Source Code 817
143 err=pthread_create(&tid, NULL, printer_thread, NULL);
144 if (err == 0)
145 err=pthread_create(&tid, NULL, signal_thread, NULL);
146 if (err != 0)
147 log_exit(err, "can’t create thread");
148 build_qonstart();
149 log_msg("daemon initialized");
150 for (;;) {
151 rset=rendezvous;
152 if (select(maxfd+1, &rset, NULL, NULL, NULL) < 0)
153 log_sys("select failed");
154 for (i = 0; i <= maxfd; i++) {
155 if (FD_ISSET(i, &rset)) {
156 /*
157 * Accept the connection and handle the request.
158 */
159 if ((sockfd = accept(i, NULL, NULL)) < 0)
160 log_ret("accept failed");
161 pthread_create(&tid, NULL, client_thread,
162 (void *)((long)sockfd));
163 }
164 }
165 }
166 exit(1);
167 }
[143 – 149] We create one thread to handle signals and one thread to communicate with
the printer.(By restricting printer communication to one thread, we can
simplify the locking of the printer-related data structures.) Then we call
build_qonstartto search the directories in/var/spool/printerfor
any pending jobs. For each job that we find on disk, we will create a
structure to let the printer thread know that it should send the file to the
printer.Atthis point, we aredone setting up the daemon, so we log a
message to indicate that the daemon has initialized successfully.
[150 – 167] We copy therendezvous fd_setstructuretorsetand callselectto
wait for one of the file descriptors to become readable. Wehave to copy
rendezvous,becauseselectwill modify thefd_setstructurethat we
pass to it to include only those file descriptors that satisfy the event. Since
the sockets have been initialized for use by a server,areadable file descriptor
means that a connect request is pending. Afterselectreturns, we check
rsetfor a readable file descriptor.If we find one, we callacceptto accept
the connection. If this fails, we log an error message and continue checking
for morereadable file descriptors. Otherwise, we create a thread to handle
the client connection. Themainthread loops, farming requests out to other
threads for processing, and should never reach theexitstatement.