dup() / dup2()¶
Purpose¶
dup() and dup2() duplicate file descriptors.
They are useful when redirecting standard input/output, preserving fd handles, or preparing child process I/O after fork().
Header¶
Prototype¶
Parameters¶
| Parameter | Description |
|---|---|
oldfd |
Existing file descriptor to duplicate. |
newfd |
Target descriptor number for dup2(). |
Return Value¶
Returns the new file descriptor on success. Returns -1 on failure and sets errno.
Minimal Example¶
Common Pitfalls¶
- Forgetting that duplicated fds refer to the same open file description.
- Not closing duplicated fds after use.
- Accidentally overwriting standard descriptors with
dup2().