Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

806 Communicating with a Network Printer Chapter 21


120 /*
121 * "Timed" read - timout specifies the number of seconds to wait
122 * per read call before giving up, but read exactly nbytes bytes.
123 * Returns number of bytes read or -1 on error.
124 *
125 * LOCKING: none.
126 */
127 ssize_t
128 treadn(int fd, void *buf, size_t nbytes, unsigned int timout)
129 {
130 size_t nleft;
131 ssize_t nread;

132 nleft=nbytes;
133 while (nleft > 0) {
134 if ((nread = tread(fd, buf, nleft, timout)) < 0) {
135 if (nleft == nbytes)
136 return(-1); /* error, return -1 */
137 else
138 break; /* error, return amount read so far */
139 } else if (nread == 0) {
140 break; /* EOF */
141 }
142 nleft -= nread;
143 buf += nread;
144 }
145 return(nbytes-nleft); /* return >= 0 */
146 }

[120 – 146] We also provide a variation oftread,calledtreadn,that reads exactly the
number of bytes requested. This is similar to thereadnfunction described
in Section 14.7, but with the addition of the timeout parameter.
To read exactlynbytesbytes, we have to be prepared to make multiple calls
toread.The difficult part is trying to apply a single timeout value to
multiple calls toread.Wedon’t want to use an alarm, because signals can
be messy to deal with in multithreaded applications. We can’t rely on the
system updating thetimevalstructure on return fromselectto indicate
the amount of time left, because many platforms do not support this
behavior (Section 14.4.1). Thus, we compromise and define the timeout
value in this case to apply to an individualreadcall. Instead of limiting the
total amount of time we wait, it limits the amount of time we’ll wait in every
iteration of the loop. The maximum time we can wait is bounded by (nbytes
×timout)seconds (worst case, we’ll receive only 1 byte at a time).
We usenleftto recordthe number of bytes remaining to be read. Iftread
fails and we have received data in a previous iteration, we break out of the
whileloop and return the number of bytes read; otherwise, we return−1.
Free download pdf