Linux/UNIX列出用于处理的打开文件

时间:2020-01-09 10:40:26  来源:igfitidea点击:

如何使用命令行选项列出Linux或UNIX进程的所有打开文件?
在Linux下如何显示每个进程的打开文件?

Linux和类Unix操作系统都附带各种实用程序,以查找与该进程关联的打开文件。

UNIX列出要处理的打开文件

首先使用ps命令命令获取进程的PID,执行:

$ ps -aef | grep {process-name}
$ ps -aef | grep httpd

接下来将此PID传递给pfiles命令,

$ pfiles {PID}
$ pfiles 3533

有关更多信息,请参见pfiles命令文档。

FreeBSD列出每个进程的打开文件

在FreeBSD上,将fstat命令和ps命令一起使用:

# ps aux | grep -i openvpn # filter outputs using the grep command #
# fstat -p {PID}
# fstat -p 1219

我们可以使用wc命令如下计算openvpn进程的打开文件数:

# fstat -p 1219 | grep -v ^USER | wc -l

-p选项传递给fstat,以报告指定进程打开的所有文件。

FreeBSD pstat命令的作用

Linux列出要处理的打开文件

首先,您需要找出过程的PID。
只需使用以下任一命令即可获取进程ID:

# ps aux | grep {program-name}

或者

$ ps -C {program-name} -o pid=

例如,找出firefox Web浏览器的PID,执行:

$ ps -C firefox -o pid=

输出:

7857

要列出用于Firefox处理的opne文件,请执行:

$ ls -l /proc/7857/fd

输出示例:

total 0
lr-x------ 1 Hyman Hyman 64 2008-03-05 22:31 0 -> /dev/null
l-wx------ 1 Hyman Hyman 64 2008-03-05 22:31 1 -> pipe:[18371]
lr-x------ 1 Hyman Hyman 64 2008-03-05 22:31 10 -> /usr/lib/firefox/firefox
l-wx------ 1 Hyman Hyman 64 2008-03-05 22:31 2 -> pipe:[18371]

对于特权进程,请使用sudo命令,并在Linux上使用wc命令对打开的文件进行计数,如下所示:

# Get process pid 
sudo ps -C Xorg -o pid
sudo ls -l /proc/${pid-here}/fd
# Say pid is 9497 for Xorg, then
sudo ls -l /proc/9497/fd | wc -l

我们也可以使用bash进行循环,如下所示:

# Linux Count and List Open Files for Nginx Process #
SEARCH="nginx"
for i in $(ps -C "${SEARCH}" -o pid | grep -v PID)
do  
     echo "PID # ${i} open files count : $(sudo ls -l /proc/${i}/fd | wc -l)"
done

列出Linux上的打开文件

使用lsof显示使用最多文件句柄的进程

lsof命令列出了所有Linux发行版或类UNIX操作系统下的打开文件。
执行以下命令以列出进程ID 351的打开文件:

$ lsof -p 351

在此示例中,显示并计算Linux操作系统或服务器上前10个进程的所有打开文件:

# lsof | awk '{print }' | sort | uniq -c | sort -r | head
## force numeric sort by passing the '-n' option to the sort ##
# lsof | awk '{print }' | sort | uniq -c | sort -r -n | head
3884 nginx
    643 php-fpm7.
    370 memcached
     90 rsyslogd
     81 systemd
     63 systemd-j
     58 systemd-r
     55 systemd-n
     50 systemd-l
     48 networkd

其中:

  • lsof运行lsof以显示所有打开的文件并将输出发送到awk
  • awk'{print $1}'显示第一个字段,即仅进程名称
  • uniq -c省略重复的行,而前缀行的出现次数
  • sort -r反向排序
  • head显示前10个进程以及打开的文件数