What does dup2() do in C
Asked Answered
N

1

10

I looked it up in the man page but I still don't get it...

let's say you have dup2(f1,0). Does that switch filedesc.1 with stdin and then locks stdin?

Nate answered 2/7, 2014 at 18:29 Comment(8)
What does this have to do with bash?Lavenialaver
Unix, pipes, my apologiesNate
"dup2() makes newfd be the copy of oldfd, closing newfd first if necessary"Peculation
int dup2(int oldfd, int newfd);Peculation
possible duplicate of How to change the fd associated with the stdin file descriptor?Peculation
Here's more info: #14543943Peculation
@staticx Your proposed duplicate doesn't explain anything. While there may well be a duplicate among all the questions that mention dup2, this isn't it.Totalizer
@Gilles: I posted a second link, can't take back my proposed duplicate nowPeculation
A
31

dup2 doesn't switch the file descriptors, it makes them equivalent. After dup2(f1, 0), whatever file was opened on descriptor f1 is now also opened (with the same mode and position) on descriptor 0, i.e. on standard input.

If the target file descriptor (here, 0) was open, it is closed by the dup2 call. Thus:

before                         after
0: closed, f1: somefile        0: somefile, f1:somefile
0: otherfile, f1: somefile     0: somefile, f1:somefile

No locking is involved.

dup2 is useful (among other things) when you have part of a program that reads or write from the standard file descriptors. For example, suppose that somefunc() reads from standard input, but you want it to read from a different file from where the rest of the program is getting its standard input. Then you can do (error checking omitted):

int save_stdin = dup(0);
int somefunc_input_fd = open("input-for-somefunc.data", O_RDONLY);
dup2(somefunc_input_fd, 0);
/* Now the original stdin is open on save_stdin, and input-for-somefunc.data on both somefunc_input_fd and 0. */
somefunc();
close(somefunc_input_fd);
dup2(save_stdin, 0);
close(save_stdin);
Ashti answered 2/7, 2014 at 19:20 Comment(1)
thorough explanation, tnxNate

© 2022 - 2024 — McMap. All rights reserved.