lsof -p PID

works fine to list all files open by a single process, but I need to list all currently open files by a specific master process AND its children processes. What is the best way to do this? If this isn't possible with lsof, what other way could I accomplish this?

  • 1
    Does "children" include all descendants or just direct children? – NickD Jan 7 '18 at 2:42
  • 2
    Did you try options -a -K ? – ridgy Jan 7 '18 at 18:44

For the $pid and its (direct) children, you could do:

lsof -p "$({ echo "$pid"; pgrep -P "$pid"; } | paste -sd , -)"

pgrep, like lsof is not a standard command but is found on quite a few systems these days.

For all the descendants (children, grand-children, etc), you could use pstree to get the list of pids, however that would not be foolproof as its output cannot be parsed reliably. You could use a helper function like:

descendants() {
  ps -Ao pid= -o ppid= | PID=$1 perl -lae '
    push @{$children{$F[1]}}, $F[0];
    sub tree {
      my @pids=($_[0]);
      push @pids, tree($_) for @{$children{$_[0]}};
      return @pids;
    END{print for tree $ENV{PID}}'

And then call:

lsof -p "$(descendants "$pid" | paste -sd, -)"

Semi-manual fashion:

$ pstree -p PID

gather the PIDs from the above

$ lsof -p pid1,pid2,pid3,...

Alternatively, loop over the output of ps --ppid 1413 -o pid= until it's empty, in order to gather the list of pids.

  • This works, but wont the process ID change whenever the machine is rebooted, or the process is killed/restarted? – Jeff S Jan 7 '18 at 1:49
  • Well sure. You said “a specific master process”, so I thought you had one in mind. – Jeff Schaller Jan 7 '18 at 1:53
  • Yeah, I guess that was the way I worded it. I'm trying to set up a script that will be usable if the machine gets rebooted or the process gets killed. Is referencing PID not the right way to accomplish this? Should I have the script reference the processes some other way? By process name maybe? I feel like there should be a better way to have an absolute reference. – Jeff S Jan 7 '18 at 2:01
  • Something like pgrep against a full path could help; depends on how the process starts. – Jeff Schaller Jan 7 '18 at 2:38
lsof -n | awk '{print $2}' | sort | uniq -c | sort -nr | grep PARENT_PID

since lsof can list open files both parent process and subprocess. the output of second column is parent process

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.