Briefly compare the dup of function and dup2 of function in C language

  • 2020-04-02 03:19:18
  • OfStack

C dup() function: copies the file descriptor
The header file:


#include <unistd.h>

Definition function:


int dup (int oldfd);

Function description: dup () is used to copy the parameter oldfd refers to file descriptors, and return to it. The new file descriptors and parameter oldfd refers to the same file, all Shared lock, read/write position and authority or flag. For example, when using lseek () to a file descriptors, another location file description words, speaking, reading and writing will be along with the change. However, is not Shared between file description words close - on - the exec flag.

Return value: returns the smallest and unused file descriptor when copied successfully. Returns -1 for errors and errno stores the error code.

Error code: EBADF parameter fd is not a valid file descriptor, or the file is closed.

C dup2() function: copy the file descriptor
The header file:


 #include <unistd.h>

Definition function:


int dup2(int odlfd, int newfd);

Function description: dup2 () is used to copy the parameter oldfd refers to file descriptors, and copy it to the parameters of a return after newfd. If the parameter newfd is an already open file descriptors, newfd refers to the file will be closed. Dup2 () to copy the file description words, with the original file descriptors for sharing all kinds of file status, details refer to dup ().

Return value: returns the smallest and unused file descriptor when copied successfully. Returns -1 for errors and errno stores the error code.

Note: dup2() is equivalent to calling FCNTL (oldfd, F_DUPFD, newfd).

Error code: EBADF parameter fd is not a valid file descriptor, or the file is closed


Related articles: