Wednesday, September 21, 2011

Getting file position using /proc

As I wrote in my post of 2009, "Often there is a need to check what's some process doing right now". That time I discovered this simple way of checking which file a process(e.g. grep) was using.

Another trick of this kind is to get a file position. This is a very common scenario. For example, you want to know the progress of unpacking of a really huge .gz file. You cannot just estimate this by analyzing the size of the data already unpacked.

Getting file position is as easy as getting a name of an open file. Thanks to Miklos Szeredi starting from Linux-2.6.22 this info can be obtained from /proc/PID/fdinfo/FD:

$ python
>>> f=open('/home/turist/work/big.txt')
>>> f.seek(1234)

(in another terminal, 3580 is python's PID)
$ ls -al /proc/3580/fd/
total 0
dr-x------ 2 turist turist  0 2011-09-21 14:40 .
dr-xr-xr-x 7 turist turist  0 2011-09-21 14:40 ..
lrwx------ 1 turist turist 64 2011-09-21 14:40 0 -> /dev/pts/1
lrwx------ 1 turist turist 64 2011-09-21 14:40 1 -> /dev/pts/1
lrwx------ 1 turist turist 64 2011-09-21 14:40 2 -> /dev/pts/1
lr-x------ 1 turist turist 64 2011-09-21 14:40 3 -> /home/yevgen/work/big.txt

(so 3 is our file descriptor, we will use it now)

$ cat /proc/3580/fdinfo/3
pos:	1234
flags:	0100000
Easy!

1 comment: