Can someone explain what dup() in C does?

2019-03-08 11:21发布

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 numbers to keep track of file locations and their direction(input/output). Wouldn't it be easier to just

fd=fd2;

Whenever we want to duplicate a file descriptor?

And something else..

dup() uses the lowest-numbered unused descriptor for the new descriptor.

Does that mean that it can also take as value stdin, stdout or stderr if we assume that we have close()-ed one of those?

标签: c pipe dup2 dup
8条回答
时光不老,我们不散
2楼-- · 2019-03-08 11:58

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-03-08 12:04

Just a tip about "duplicating standard output".

On some Unix Systems (but not GNU/Linux)

fd = open("/dev/fd/1", O_WRONLY);

it is equivalent to:

fd = dup(1);
查看更多
登录 后发表回答