Schedule
Labs
Assignments
TA office hours
Topic videos
Some course notes
Extra problems
Lecture recordings
Answer: dup2(8,8) doesn't duplicate the file descriptor, and then close(8) closes the file descriptor we just opened. So we don't actually have the desired file open on fd 8 after all. (The call dup2(8,8) in fact does nothing. But if you assumed it closed fd 8, well, that's a reasonable guess and the answer is the same, that in the end the file "foo" is not actually open as desired.)
And how do you fix this bug?
Answer: Put the dup2 and close inside an "if fd != 8":
if (fd != 8) { dup2(fd, 8); close(fd); }Because if the fd does happen to be 8, there's no need to renumber, the file is already open on file descriptor 8 as desired.