Get list of open files (descriptors) in OS X

2019-01-14 05:18发布

I would like to get a list of open files in a process on os x (10.9.1). In Linux I was able to get this from /proc/PID/fd. However I'm not sure how to get the same on OS X. I found that the procfs is not present on the OS X (by default. possible implementations present, but I do not want to go that way).

So how do I get (natively) the list of open files in a process on OS X. One way is lsof. is there any other support available? please let me know where I can get more info on this.

Thanks.

7条回答
够拽才男人
2楼-- · 2019-01-14 05:56

The clean and simple approach to inspect the current process (i.e. the equivalent of /proc/self/fd on Linux) is to use ls /dev/fd/:

e.g.

$ touch "file"
$ exec 3<>file

$ ls /dev/fd/    

0 1 2 3
查看更多
来,给爷笑一个
3楼-- · 2019-01-14 05:57

List open files on /Volumes/VolumeName:

lsof | grep "/Volumes/VolumeName"
查看更多
beautiful°
4楼-- · 2019-01-14 06:04

At least on OSX 10.10 (Yosemite, didn't check on Mavericks), you can get the list of open files by process via the default activity monitor application. Just double click on the relevant process on the list and select "Open Files and Ports" tab on the popup.

Tip: cmd+f shortcut on that pane allows for searching and highlighting on the content.

查看更多
Summer. ? 凉城
5楼-- · 2019-01-14 06:04

This works for some things:

sudo fs_usage | grep dev

for /dev/ files or similar.

查看更多
劳资没心,怎么记你
6楼-- · 2019-01-14 06:05

Since you asked "Is there any other support [than lsof] available?", try this:

Create a command line tool using the "proc_pidinfo" C API referenced in the selected answer to this question: How can I programmatically get the list of open file descriptors for a given PID on OS X?

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.

查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-01-14 06:10

I had a hard time getting Activity Monitor to show open files for a process that was running as root (via sudo). The original question mentions lsof, and it does the trick exactly. If you know the process name or PID, it's super quick.

Find processes by name:

lsof -c processname

Find processes by PID:

lsof -p 123

(Prefix with sudo as needed, such as if you are not the owner of the process.)

查看更多
登录 后发表回答