开发者

What does dup2 actually do in this case?

I need some clarification here: I have some code like this:

child_map[0] = fileno(fd[0]);
..
pid = fork();
if(pid == 0)
/* child process*/
dup2(child_map[0], STDIN_FILENO);

Now, will STDIN_FILENO and child_map[0] point to the same file descriptor ? Wil开发者_StackOverflow中文版l the future inputs be taken from the file pointed to by child_map[0] and STDIN_FILENO ? I thought STDIN_FILENO means the standard output(terminal).


After the dup2(), child_map[0] and STDIN_FILENO will continue to be separate file descriptors, but they will refer to the same open file description. That means that if, for example, child_map[0] == 5 and STDIN_FILENO == 0, then both file descriptor 5 and 0 will remain open after the dup2().

Referring to the same open file description means that the file descriptors are interchangeable - they share attributes like the current file offset. If you perform an lseek() on one file descriptor, the current file offset is changed for both.

To close the open file description, all file descriptors that point to it must be closed.

It is common to execute close(child_map[0]) after the dup2(), which leaves only one file descriptor open to the file.


It causes all functions which read from stdin to get their data from the specified file descriptor, instead of the parent's stdin (often a terminal, but could be a file or pipe depending on shell redirection).

In fact, this is how a shell would launch processes with redirected input.

e.g.

cat somefile | uniq

uniq's standard input is bound to a pipe, not the terminal.


STDIN_FILENO is stdin, not stdout. (There's a STDOUT_FILENO too.) Traditionally the former is 0 and the latter 1.

This code is using dup2() to redirect the child's stdin from another file descriptor that the parent had opened. (It is in fact the same basic mechanism used for redirection in shells.) What usually happens afterward is that some other program that reads from its stdin is execed, so the code has set up its stdin for that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜