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:

fdnamemeaning
0stdinstandard input
1stdoutstandard output
2stderrstandard 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) — duplicates oldfd into the lowest available fd. Both fds now refer to the same file.
  • dup2(oldfd, newfd) — duplicates oldfd into exactly newfd. If newfd is already open, it is silently closed first. If oldfd == newfd, return newfd without 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.