Lesson 9 of 15
File Descriptor Table
File Descriptor Table
Every process has a file descriptor table — an array where each index is a file descriptor (fd) and each slot points to an open file. FDs 0, 1, and 2 are pre-assigned:
| fd | name | meaning |
|---|---|---|
| 0 | stdin | standard input |
| 1 | stdout | standard output |
| 2 | stderr | standard error |
When you call open(), the kernel scans the table for the lowest free slot starting at 3 and returns that fd. close() marks the slot free again.
dup and dup2
Two important system calls duplicate file descriptors:
dup(oldfd)— duplicatesoldfdinto the lowest available fd. Both fds now refer to the same file.dup2(oldfd, newfd)— duplicatesoldfdinto exactlynewfd. Ifnewfdis already open, it is silently closed first. Ifoldfd == newfd, returnnewfdwithout doing anything.
This is how shells implement I/O redirection:
// Redirect stdout to a file:
int fd = open("out.txt", ...);
dup2(fd, 1); // fd 1 (stdout) now points to "out.txt"
close(fd); // original fd no longer needed
Your Task
Implement my_open, my_close, my_getname, my_dup, and my_dup2 for a 16-entry file descriptor table (fds 0–15, with 0/1/2 pre-reserved).
TCC compiler loading...
Loading...
Click "Run" to execute your code.