Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux proc/pid/fd for stdout is 11?

Executing a script with stdout redirected to a file. So /proc/$$/fd/1 should point to that file (since stdout fileno is 1). However, actual fd of the file is 11. Please, explain, why.

Here is session:

$ cat hello.sh
#!/bin/sh -e
ls -l /proc/$$/fd >&2

$ ./hello.sh > /tmp/1
total 0
lrwx------ 1 nga users 64 May 28 22:05 0 -> /dev/pts/0
lrwx------ 1 nga users 64 May 28 22:05 1 -> /dev/pts/0
lr-x------ 1 nga users 64 May 28 22:05 10 -> /home/me/hello.sh
l-wx------ 1 nga users 64 May 28 22:05 11 -> /tmp/1
lrwx------ 1 nga users 64 May 28 22:05 2 -> /dev/pts/0
like image 547
stepancheg Avatar asked May 28 '11 18:05

stepancheg


People also ask

What is in proc PID FD?

find(1) with the -inum option can be used to locate the file. /proc/[pid]/fd/ This is a subdirectory containing one entry for each file which the process has open, named by its file descriptor, and which is a symbolic link to the actual file.

What is FD in proc?

The abbreviation “fd” stands for file descriptor. What is /dev/pts/6 , and why do 0 , 1 , and 2 all point to it? File descriptors 0 , 1 and 2 are the three standard streams) that all programs expect to find: standard input (stdin), standard output (stdout) and standard error (stderr).

What is PID and FD?

PID is process identifier, and file descriptor is file handler identifier. Specifically from Wikipedia about File Descriptors: (...) file descriptor (FD) is an abstract indicator for accessing a file. The term is generally used in POSIX operating systems.

How often is proc PID Stat updated?

In test environment, this file refreshed 1 ~ 2 sec, so I assume this file often updated by system at least 1 sec. But, In commercial servers environment, process run with high load (cpu and file IO), /proc/[pid]/stat file update period increasing even 20~60 sec!!


1 Answers

I have a suspicion, but this is highly dependent on how your shell behaves. The file descriptors you see are:

  • 0: standard input
  • 1: standard output
  • 2: standard error
  • 10: the running script
  • 11: a backup copy of the script's normal standard out

Descriptors 10 and 11 are close on exec, so won't be present in the ls process. 0-2 are, however, prepared for ls before forking. I see this behaviour in dash (Debian Almquist shell), but not in bash (Bourne again shell). Bash instead does the file descriptor manipulations after forking, and incidentally uses 255 rather than 10 for the script. Doing the change after forking means it won't have to restore the descriptors in the parent, so it doesn't have the spare copy to dup2 from.

like image 98
Yann Vernier Avatar answered Sep 28 '22 06:09

Yann Vernier