How to get open files of a subprocess?

1.4k Views Asked by At

How to get open files of a subprocess?

i opened a subprocess which generate files, i want get file descritor of these files to do fsync on them

so if i have code like this:

p = subprocess.Popen([
            'some_program'
])

the process p generate some files i can get the process id of the subprocess using:

p.pid

but how can i get fd of these files to call flush and fsync() on them?

actually i find a utility called "lsof" (list open files) but it is not installed or supported on my system, so i did not do further investigations on it, as i really need a standard way

thanks

3

There are 3 best solutions below

4
On BEST ANSWER

Each process has its own table of file descriptors. If you know that a child process has a certain file open with FD 8 (which is easy enough, just take a listing of /proc/<pid>/fd), when you do fsync(8) you are sync'ing a file of your process, not the child's.

The same applies to all functions that use file descriptors: fread, fwrite, dup, close...

To get the effect of fsync, you might call sync instead.

What you could do instead is implement some kind of an RPC mechanism. For example you could add a signal handler that makes the child run fsync on all open FDs when it receives SIGUSR1.

0
On

If you want to use a packed solution, instead of going to /proc/pid/fd, an option is to use lsof of psutils

0
On

You can't fsync on behalf of another process. Also, you probably want flushing, not fsync. You can't flush on behalf of another process either. Rethink your requirements.