Can someone explain what dup() in C does?

前端 未结 8 1096
不知归路
不知归路 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-30 23:54

    Just wanted to respond to myself on the second question after experimenting a bit.

    The answer is YES. A file descriptor that you make can take a value 0, 1, 2 if stdin, stdout or stderr are closed.

    Example:

    close(1);     //closing stdout
    newfd=dup(1); //newfd takes value of least available fd number
    

    Where this happens to file descriptors:

    0 stdin     .--------------.     0 stdin     .--------------.     0 stdin
    1 stdout   =|   close(1)   :=>   2 stderr   =| newfd=dup(1) :=>   1 newfd
    2 stderr    '--------------'                 '--------------'     2 stderr
    

提交回复
热议问题