Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

826 Communicating with a Network Printer Chapter 21


414 nw=write(fd, buf, nr);
415 if (nw != nr) {
416 res.jobid=0;
417 if (nw < 0)
418 res.retcode=htonl(errno);
419 else
420 res.retcode=htonl(EIO);
421 log_msg("client_thread: can’t write %s: %s", name,
422 strerror(res.retcode));
423 close(fd);
424 strncpy(res.msg, strerror(res.retcode), MSGLEN_MAX);
425 writen(sockfd, &res, sizeof(struct printresp));
426 unlink(name);
427 pthread_exit((void *)1);
428 }
429 }
430 close(fd);
431 /*
432 * Create the control file. Then write the
433 * print request information to the control
434 * file.
435 */
436 sprintf(name, "%s/%s/%d", SPOOLDIR, REQDIR, jobid);
437 fd=creat(name, FILEPERM);
438 if (fd < 0) {
439 res.jobid=0;
440 res.retcode=htonl(errno);
441 log_msg("client_thread: can’t create %s: %s", name,
442 strerror(res.retcode));
443 strncpy(res.msg, strerror(res.retcode), MSGLEN_MAX);
444 writen(sockfd, &res, sizeof(struct printresp));
445 sprintf(name, "%s/%s/%d", SPOOLDIR, DATADIR, jobid);
446 unlink(name);
447 pthread_exit((void *)1);
448 }

[414 – 430] We write the data that we read from the client to the data file. Ifwritefails,
we log an error message, close the file descriptor for the data file, send an
error message back to the client, delete the data file, and terminate the thread
by callingpthread_exit.Note that we do not explicitly close the socket
file descriptor.This is done for us by our thread cleanup handler as part of
the processing that occurs when we callpthread_exit.
When we receive all the data to be printed, we close the file descriptor for
the data file.
[431 – 448] Next, we create a file,/var/spool/printer/reqs/jobid, to remember the
print request. If this fails, we log an error message, send an error response to
the client, remove the data file, and terminate the thread.
Free download pdf