Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

810 Communicating with a Network Printer Chapter 21


81 req.size=htonl(nbytes);
82 if (text)
83 req.flags=htonl(PR_TEXT);
84 else
85 req.flags=0;
86 if ((len = strlen(fname)) >= JOBNM_MAX) {
87 /*
88 * Truncate the filename (+-5 accounts for the leading
89 * four characters and the terminating null).
90 */
91 strcpy(req.jobnm, "... ");
92 strncat(req.jobnm, &fname[len-JOBNM_MAX+5], JOBNM_MAX-5);
93 } else {
94 strcpy(req.jobnm, fname);
95 }

96 /*
97 * Send the header to the server.
98 */
99 nw=writen(sockfd, &req, sizeof(struct printreq));
100 if (nw != sizeof(struct printreq)) {
101 if (nw < 0)
102 err_sys("can’t write to print server");
103 else
104 err_quit("short write (%d/%d) to print server",
105 nw, sizeof(struct printreq));
106 }

[81 – 95] We storethe size of the file to be printed in the header after converting it to
network byte order.Then we do the same with thePR_TEXTflag if the file is
to be printed as plaintext. By translating these integers to network byte
order, we can run the print command on a client system while the printer
spooling daemon is running on another computer system. If these systems
use processors with different byte ordering, then the commands will still
work. (Wediscussed byte ordering in Section 16.3.1.)
We set the job name to the name of the file being printed. If the name is
longer than will fit in the job name field in the message, we copy only the
last portion of the name that will fit. This effectively truncates the beginning
portion of the name. In this case, we prepend an ellipsis to indicate that
thereweremorecharacters than would fit in the field.
[96 – 106] We send the request header to the daemon usingwriten.(Recall that we
introduced thewritenfunction in Figure14.24.) Thewritenfunction uses
multiple calls towrite, if necessary, to transmit the specified amount. If the
writenfunction returns an error or transmits less than we requested, we
print an error message and exit.
Free download pdf