ptg10805159
832 Communicating with a Network Printer Chapter 21
608 /*
609 * Single thread to communicate with the printer.
610 *
611 * LOCKING: acquires and releases joblock and configlock.
612 */
613 void *
614 printer_thread(void *arg)
615 {
616 struct job *jp;
617 int hlen, ilen, sockfd, fd, nr, nw, extra;
618 char *icp, *hcp, *p;
619 struct ipp_hdr *hp;
620 struct stat sbuf;
621 struct iovec iov[2];
622 char name[FILENMSZ];
623 char hbuf[HBUFSZ];
624 char ibuf[IBUFSZ];
625 char buf[IOBUFSZ];
626 char str[64];
627 struct timespec ts = { 60, 0 }; /* 1 minute */
628 for (;;) {
629 /*
630 * Get a job to print.
631 */
632 pthread_mutex_lock(&joblock);
633 while (jobhead == NULL) {
634 log_msg("printer_thread: waiting...");
635 pthread_cond_wait(&jobwait, &joblock);
636 }
637 remove_job(jp=jobhead);
638 log_msg("printer_thread: picked up job %d", jp->jobid);
639 pthread_mutex_unlock(&joblock);
640 update_jobno();
[608 – 627] Theprinter_threadfunction is run by the thread that communicates
with the network printer.We’ll useicpandibufto build the IPP header.
We’ll usehcpandhbufto build the HTTP header.Weneed to build the
headers in separate buffers. The HTTP header includes a length field in
ASCII, and we won’t know how much space to reserve for it until we
assemble the IPP header.We’ll usewritevto write these two headers in
one call.
[628 – 640] The printer thread runs in an infinite loop that waits for jobs to transmit to
the printer.Weuse thejoblockmutex to protect the list of jobs. If a job is
not pending, we usepthread_cond_waitto wait for one to arrive. When
ajob is ready, we remove it from the list by callingremove_job.Westill
hold the mutex at this point, so we release it and callupdate_jobnoto
write the next job number to/var/spool/printer/jobno.