Find out to which directory a process is writing

open filesprocess

This question is NOT a duplicate of this question Find out current working directory of a running process?, because the writing directory can be different from the working directory.

For example, I start two processes by running my_script.sh in ~/ twice (one right after another).

In my_script.sh, I have made it to write the output to a folder whose name is a time stamp. Hence, despite the same working directory, the two processes actually write into different directories, say ~/1212_000001/ and ~/1212_000003/. (the 1st process starts at 00:00:01 on Dec. 12 and the 2nd starts 2 seconds later)

The solution in the question linked returns me the same result ~/ for the two processes and thus fail my purpose.

How to do it?

Best Answer

This depends on how the script is writing:

  • If directly by redirection (i.e. my_script.sh > ~/1212_000001/some_file), you can use lsof -p <script-pid> and you'll see the open file on your output directory
  • Else, the output of ps axjf' will show you the pid dependencies of sub-processes launched by your script, which may give you the information immediately in command arguments or allow you to play lsof -p <sub-process-pid> on sub-processes.

Of course, if this occurs in a very short time, this method will not apply.

You can also make use of 'strace' command and look for "open" calls.

Related Question