What do the dup()
and dup2()
system calls really do? How would I use them in practice?
Asked
Active
Viewed 1.6k times
4

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278

user484457
- 4,301
- 7
- 21
- 14
-
What part don't you understand after reading the man pages and searching? – Matthew Flaschen Nov 13 '10 at 05:34
-
i was unable to understand how to use in programming and where to use – user484457 Nov 13 '10 at 05:35
-
3Have you looked at http://stackoverflow.com/questions/1720535/practical-examples-use-dup-or-dup2 or http://stackoverflow.com/questions/3918962/unix-c-dup2-question ? – Zeke Nov 13 '10 at 05:39
1 Answers
5
Both make a new file descriptor corresponding to an existing open file description. Most properties between the old and new fd (like position) are shared; the only property I can think of that's not shared is the close-on-exec flag. The difference between dup
and dup2
is that dup
assigns the lowest available file descriptor number, while dup2
lets you choose the file descriptor number that will be assigned and atomically closes and replaces it if it's already taken.

R.. GitHub STOP HELPING ICE
- 208,859
- 35
- 376
- 711
-
1Also note that `fcntl` with the `F_DUPFD` command behaves similarly to `dup2`, but does not clobber an existing fd, so it can safely be used in threaded programs when trying to create a particular fd number that's not already taken. – R.. GitHub STOP HELPING ICE Jan 07 '12 at 04:23
-
1Besides, if the file referenced by `newfd` is already open, it will be closed before the duplication is performed. – Soner from The Ottoman Empire Mar 30 '19 at 12:40
-
@snr: Not "before". Rather *atomically with respect to*. – R.. GitHub STOP HELPING ICE Mar 30 '19 at 19:11