Can someone explain what dup() in C does?

前端 未结 8 1097
不知归路
不知归路 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

    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
    

    A question arose again: How can I dup() a file descriptor that I already closed?

    I doubt that you conducted the above experiment with the shown result, because that would not be standard-conforming - cf. dup:

    The dup() function shall fail if:

    [EBADF]
    The fildes argument is not a valid open file descriptor.

    So, after the shown code sequence, newfd must be not 1, but rather -1, and errno EBADF.

提交回复
热议问题