1426 Appendix F
A call to dup2() can be rewritten as:
if (oldfd == newfd) { /* oldfd == newfd is a special case */
if (fcntl(oldfd, F_GETFL) == -1) { /* Is oldfd valid? */
errno = EBADF;
fd = -1;
} else {
fd = oldfd;
}
} else {
close(newfd);
fd = fcntl(oldfd, F_DUPFD, newfd);
}
5-6. The first point to realize is that, since fd2 is a duplicate of fd1, they both share a
single open file description, and thus a single file offset. However, because fd3 is
created via a separate call to open(), it has a separate file offset.
z After the first write(), the file contents are Hello,.
z Since fd2 shares a file offset with fd1, the second write() call appends to the
existing text, yielding Hello, world.
z The lseek() call adjusts the single file offset shared by fd1 and fd2 to point to the
start of the file, and thus the third write() call overwrites part of the existing text
to yield HELLO, world.
z The file offset for fd3 has not so far been modified, and so points to the start of
the file. Therefore, the final write() call changes the file contents to Gidday world.
Run the program fileio/multi_descriptors.c in the source code distribution for this
book to see these results.
Chapter 6
6-1. Since the array mbuf is not initialized, it is part of the uninitialized data segment.
Therefore, no disk space is required to hold this variable. Instead, it is allocated
(and initialized to 0) when the program is loaded.
6-2. A demonstration of the incorrect usage of longjmp() is provided in the file proc/
bad_longjmp.c in the source code distribution for this book.
6-3. Sample implementations of setenv() and unsetenv() are provided in the file proc/
setenv.c in the source code distribution for this book.
Chapter 8
8-1. The two getpwnam() calls are executed before the printf() output string is
constructed, and—since getpwnam() returns its result in a statically allocated buffer—
the second call overwrites the result returned by the first call.