Sunday, January 29, 2012

Power of Proc-6: open File descriptors information of a process

This post  talks about one of the interesting information proc provides, that is about the open file descriptors information of a process. Looking at this info one can tell , how many file descriptors that a process own, how many of them are files, sockets , pipes and interesting entity called inotify. I will not be covering what is inotify in this post as inotify itself will be covered as a new post in future.

Lets take an example and try to see the files that a process opened.
1. Again chose same  crond process and look at the file information.


cooltips# ps -eaf | grep crond
root      1379     1  0  2011 ?        00:00:07 crond
2. See the files in the directory "/proc/[pid]/fd"
cooltips# ls -l /proc/1379/fd
total 0
lrwx------. 1 root root 64 Jan 29 21:34 0 -> /dev/null
lrwx------. 1 root root 64 Jan 29 21:34 1 -> /dev/null
lrwx------. 1 root root 64 Jan 29 21:34 2 -> /dev/null
lrwx------. 1 root root 64 Jan 29 21:34 3 -> /var/run/crond.pid
lrwx------. 1 root root 64 Jan 29 21:34 4 -> socket:[9759032]
lr-x------. 1 root root 64 Jan 29 21:34 5 -> inotify
Lets go through one by one...
 the directory "fd" contains all links to files.



fds 0,1,2 are refers to stdin,stdout,stderr
Since crond is a daemon , all these descriptors are close and reopened to point "/dev/null". This is a usual process of closing descriptors 0,1,2 for a daemon process.

File descriptor 3 is a file opened for "/var/run/crond.pid"

File descriptor "4" is a socket.

File descriptor "5" is inotify instance. We will cover about inotify in later post but for now assume that this is also a kind of file descriptor.

These all filedescriptor numbers are the resulted descriptors by open or socket call.

Let me take you through another example, Lets see the files opened by "testfd"

cooltips# cat testfd.c
main()
{
while (1 );
}
cooltips# gcc testfd.c -o testfd
cooltips# ./testfd &
[1] 28634
cooltips# ls -l /proc/28634/fd
total 0
lrwx------. 1 root root 64 Jan 29 21:47 0 -> /dev/pts/2
lrwx------. 1 root root 64 Jan 29 21:47 1 -> /dev/pts/2
lrwx------. 1 root root 64 Jan 29 21:47 2 -> /dev/pts/2

Look at the code, it just has a infinite loop. Compile  and run it.
Look at the fd directory in proc file. 0,1,2 file descriptors are opened , pointing to tty and they are stdin,stdout and stderr respectively. This indicates each process by default own these file descriptors.

Hope you liked it !!
Please leave some comments, join for more tips.

Pin It
Related Posts Plugin for WordPress, Blogger...