Can someone explain what dup() in C does?

前端 未结 8 1085
不知归路
不知归路 2021-01-30 23:34

I know that dup, dup2, dup3 \"create a copy of the file descriptor oldfd\"(from man pages). However I can\'t digest it.

As I know file descriptors are just

8条回答
  •  余生分开走
    2021-01-31 00:00

    The single most important thing about dup() is it returns the smallest integer available for a new file descriptor. That's the basis of redirection:

    int fd_redirect_to = open("file", O_CREAT);
    close(1); /* stdout */
    int fd_to_redirect = dup(fd_redirect_to); /* magically returns 1: stdout */
    close(fd_redirect_to); /* we don't need this */
    

    After this anything written to file descriptor 1 (stdout), magically goes into "file".

提交回复
热议问题