How can I programmatically get the list of open file descriptors for a given PID on OS X?
Asked Answered
M

1

8

Everything I've seen says to use lsof -p, but I'm looking for something that doesn't require a fork/exec.

For example on Linux one can simply walk /proc/{pid}/fd.

Moshe answered 23/3, 2013 at 5:1 Comment(2)
Have you checked out the lsof source code?Asta
I dug into it for 15 minutes or so, but I am pretty terrible at C and couldn't make much sense of it. I'll keep poking at it, and if I come up with something, I'll post it as an answer myself :)Moshe
B
9

You can use proc_pidinfo with the PROC_PIDLISTFDS option to enumerate the files used by a given process. You can then use proc_pidfdinfo on each file in turn with the PROC_PIDFDVNODEPATHINFO option to get its path.

Bukharin answered 23/3, 2013 at 6:11 Comment(3)
Are there any good man pages or other documentation on this API? I've been ctags-ing my way round /usr/include and read that example you provided, but it's pretty terse.Moshe
There's not any documentation that I'm aware. sys/proc_info.h seems relatively self-explanatory in terms of interpreting the information available from the system calls, and the implementation of the system calls is available in the kernel open source if you want to understand more about how it all works.Bukharin
There is now whole source of lsof tool on github: github.com/lsof-org/lsof which covers basically everything regarding getting information about the process FDs and moreLister

© 2022 - 2024 — McMap. All rights reserved.