29
$ ls -og /proc/self /proc/self/fd
lrwxrwxrwx 1 64 Jun 18 11:12 /proc/self -> 32157

/proc/self/fd:
total 0
lrwx------ 1 64 Jun 22  2012 0 -> /dev/tty1
lrwx------ 1 64 Jun 22  2012 1 -> /dev/tty1
lrwx------ 1 64 Jun 22  2012 2 -> /dev/tty1
lr-x------ 1 64 Jun 22  2012 3 -> /proc/32157/fd

What is the file descriptor 3 assigned by default?

3 Answers 3

50

Nothing: there are three standard file descriptions, STDIN, STDOUT, and STDERR. They are assigned to 0, 1, and 2 respectively.

What you are seeing there is an artifact of the way ls(1) works: in order to read the content of the /proc/self/fd directory and display it, it needs to open that directory.

That means it gets a file handle, typically the first available ... thus, 3.

If you were to run, say, cat on a separate console and inspect /proc/${pid}/fd for it you would find that only the first three were assigned.

0
-1

This can also be used to read pipelines of running processes.

$ head /proc/21028/fd/3
declare -ax a_name='([0]="
8006333 (10.161.154.1)" [1]="

6006583 (10.179.231.1)" [2]="

9001437 (10.125.167.1)" [3]="

2003192 (10.138.247.1)" [4]="

4005015 (10.120.139.1)" [5]="


$ grep -n printf pol-grab.sh  | grep ^54
54:            export add_the_name="$(printf "%s\n" "$(declare -p a_name)")"
0
-1
    #include <fcntl.h>
    #include <stdio.h>
    
    int main(void)
    {
        int     fd1;
        int     fd2;
        char    buffer1[] = "a.txt";
        char    buffer2[] = "b.txt";
    
        fd1 = open(buffer1, O_WRONLY);
        fd2 = open(buffer2, O_WRONLY);
        printf("%d\n", fd1);
        printf("%d\n", fd2);
    }

You can create two different files(a.txt and b.txt) and when you use open() it will get different File descriptor, for me I got 3,4

3
4

Because 0,1,2 have default value and meaning

  • 0 : STDIN(standard input)
  • 1 : STDOUT (standard output)
  • 2 : STDERR (standard error)
2
  • Whilst this is true, it doesn't answer the question that was asked. Commented May 23, 2023 at 13:29
  • if you read and understabd other answers, this is noise Commented May 27, 2023 at 19:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .