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.
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
who.txt was opened by the process with PID 1288, which is the