ptg10805159
Section 21.5 Source Code 811
107 /*
108 * Now send the file.
109 */
110 while ((nr = read(fd, buf, IOBUFSZ)) != 0) {
111 nw=writen(sockfd, buf, nr);
112 if (nw != nr) {
113 if (nw < 0)
114 err_sys("can’t write to print server");
115 else
116 err_quit("short write (%d/%d) to print server",
117 nw, nr);
118 }
119 }
120 /*
121 * Read the response.
122 */
123 if ((nr = readn(sockfd, &res, sizeof(struct printresp))) !=
124 sizeof(struct printresp))
125 err_sys("can’t read response from server");
126 if (res.retcode != 0) {
127 printf("rejected: %s\n", res.msg);
128 exit(1);
129 } else {
130 printf("job ID %ld\n", (long)ntohl(res.jobid));
131 }
132 }
[107 – 119] After sending the header to the daemon, we send the file to be printed. We
read the fileIOBUFSZbytes at a time and usewritento send the data to the
daemon. As with the header, if the write fails or we write less than we
expect, we print an error message and exit.
[120 – 132] Once we have sent the file to be printed to the print spooling daemon, we
read the daemon’s response. If the print request failed, the return code
(retcode)will be nonzero, so we print the textual error message included
in the response. If the request succeeded, we print the job ID so that the user
knows how to refer to the request in the future. (Writing a command to
cancel a pending print request is left as an exercise; the job ID can be used in
the cancellation request to identify the job to be removed from the print
queue. See Exercise 21.5.) When submit_file returns to the main
function, we exit, indicating success.
Note that a successful response from the daemon does not mean that the
printer was able to print the file; it merely means that the daemon
successfully added the print job to the queue.
This completes our look at the print command. The last file we will look at is the C
source file for the printer spooling daemon.