Unformatted text preview: m the disk, and stores it in a buffer in main memory. Subsequent requests to read from the stream are served from the buffer rather than disk. The fflush function empties the buffer associated with a stream. The latter three functions use the Unix I/O lseek function to reset the current ﬁle position. Restriction 2: An output function cannot follow an input function without an intervening call to fseek, fsetpos, or rewind, unless the input function encounters an end-of-ﬁle. ¯ These restrictions pose a problem for network applications because it is illegal to use the lseek function on a network socket. The ﬁrst restriction on stream I/O can be worked around by a discipline of ﬂushing 12.5. THE SOCKETS INTERFACE 629 the buffer before every input operation. The only way to work around the second restriction is to open two streams on the same open socket descriptor, one for reading and one for writing.
1 2 3 4 FILE *fpin, *fpout; fpin = fdopen(sockfd, "r"); fpout = fdopen(sockfd, "w"); However, this approach has problems as well, because it requires the application to call fclose on both streams in order to free the memory resources associated with each stream and avoid a memory leak:
1 2 fclose(fpin); fclose(fpout); Each of these operations attempts to close the same underlying socket descriptor, so the second close operation will fail. While this is not necessarily a fatal error in a sequential program, closing the same descriptor twice in a threade...
View Full Document