Home > bash > Which process opened a file?

Which process opened a file?

Ever wondered who (which process) opened a given file? There is a Unix command to answer this question called lsof (“list open files”). Read more about it at wikipedia.

Demo
Execute the following script:

#!/usr/bin/env python3

# who.py

def main():
    f = open("/tmp/who.txt", "w")
    input("Press ENTER to continue...")
    f.close()

#####

if __name__ == "__main__":
    main()

Make it executable and run it. In another terminal issue the command “lsof /tmp/who.txt“. You’ll get a similar output:

$ cd /tmp

$ lsof who.txt 
COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
python3 1288  jabba    3w   REG   0,32        0   27 who.txt

$ ps 1288
  PID TTY      STAT   TIME COMMAND
 1288 pts/0    S+     0:00 python3 ./who.py

The file who.txt was opened by the process with PID 1288, which is the who.py script.

Advertisements
Categories: bash Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: