linuxfiletrace

Linux - How to track all files accessed by a process?


Is there a way to track all file I/O for a given process? All I really need is the locations of files being read from/written to from a given process (and ideally if it was a read or write operation although that's not as important).

I can run the process and track it rather than needing to attach to an existing process which I would assume is significantly simpler. Is there any kind of wrapper utility I can run a process though that will monitor file access?


Solution

  • lsof:

    Try doing this as a starter :

    lsof -p <PID>
    

    this command will list all currently open files, fd, sockets for the process with the passed process ID.

    For your special needs, see what I can offer as a solution to monitor a php script :

    php foo.php & _pid=$!
    lsof -r1 -p $_pid
    kill %1 # if you want to kill php script
    

    strace:

    I recommend the use of strace. Unlike lsof, it stays running for as long as the process is running. It will print out which syscalls are being called when they are called. -e trace=file filters only for syscalls that access the filesystem:

    sudo strace -f -t -e trace=file php foo.php
    

    or for an already running process :

    sudo strace -f -t -e trace=file -p <PID>