I'm baffled about file descriptors. I understand that to copy them, we need the system call dup2() or dup(). But why can't we just copy them by assigning old values to new variables? For instance, why can we do this
int f[2];
pipe(f); // I call pipe just to create two file descriptors, nothing special
int new_descriptor = f[0]; // this line is where I'm confused
Is is because the integers that f[0],f[1] have specific meaning, and are some sort of encoded? Thanks!
You can copy file descriptors by assignment. What you can't do is change the file that a specific file descriptor number (such as 1
) refers to — to do that, you need dup()
or dup2()
— or fcntl()
, or close()
. (Calls such as open()
or pipe()
don't affect any already-open file descriptors; they return a new one not previously in use.)
One way to look at it: there's nothing distinctive about the variable that holds the file descriptor number — any int
variable holding the same number can be used as a file descriptor. But changing the file that the file descriptor refers to is a much more complex job and requires a system call.