0

I think this post is not off-topic.We had three traditional file descriptors in Unix contexts:

0 == STDIN
1 == STDOUT
2 == STDERR

But in new articles, blogs, posts, answers, or so on, I read more than above FDs, For example:
find out which file descriptors share the same “open file description”
Why is using a shell loop to process text considered bad practice?
I/O Redirection
Using exec
File descriptors & shell scripting
However Gilles answered in last link, But after some googling I didn't found a reference about the given FDs. Also when I use the following hack :

root@debian:/home/mohsen# ls /dev/fd/
0  1  2  3

I don't watch more than 4 , But I saw 4 5 or 7 in some examples, I have the following three serious question:

  1. What's /dev/fd/3 FD?
  2. Where're the rest of them?
  3. Do you know a related reference about rest of them?
2

Any time you open a file (or anything that you can open like a file, like a socket) you get a file descriptor, which is represented by an int. The first 3 are automatically created for a process as stdin, stdout and stderr. Any other files that are opened get other descriptors. I suspect that it just increments the number each time, but I don't know if that's a reliable phenomenon or not. So 3 and 4 would be the first 2 files that were opened by the process. And 7 would be the 5th file opened.

  • 1
    File handles (that is, the fd numbers) are reused. If you open a file and get the descriptor 3, then close it, then open another file, you will again get the descriptor 3 (even though the descriptor now refers to a different file). There are some "deep" reasons for that, and some not-so-deep reasons. The deep reasons involve descriptor inheritance and what happens with daemon processes and the like. The main not-so-deep reason is that file descriptors available to a process are a finite resource, and you definitely want to avoid leaking them. – lcd047 May 20 '15 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.