Dup/dup2
Objectives
We would like to :
Learn about dup.
Notes
This is 5.5
int dup(int oldfd);
Will copy the old file descriptor into the next available location.
This will lead to two file descriptors pointing at the same location in the open file table.
You need unistd.h
Return,
The new descriptor if successful
-1 if fail
Frequently you see
fd = open(...); close(STDOUT_FILENO); dup(fd);
This will close stdout
Then copy the newly opened file descriptor down, so the file becomes stdout.
But this is subject to a race condition, and there is a better call.
int dup2(int oldfd, int newfd);
Will dup oldfd to newfd if possible.
If newfd is open, it will be closed.
Essentially close then dup
But not subject to race conditions.
Gaze upon
dupDemo.cpp
if you will!