如何从lsof访问PID。

Zac*_*ack 6 bash terminal

给定以下命令,lsof -i:1025我得到:

COMMAND   PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
ruby    12345 john   11u  IPv4 0xb2f4161230e18fd57      0t0  TCP localhost:foobar (LISTEN)
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写脚本来获取该PID(12345)并杀死它。目前,我必须运行lsof -i:1025,获取该PID,然后运行kill -9 12345

fab*_*nto 26

lsof的(8)手册页说:

   -t       specifies that lsof should produce terse output with process
            identifiers only and no header - e.g., so that the output
            may be piped to kill(1).  -t selects the -w option.
Run Code Online (Sandbox Code Playgroud)

您可以使用lsof -t -i:1025 | xargs kill -9.

  • 很有魅力!`lsof -ti:1025` 也有效。 (3认同)

blm*_*blm 7

就像是:

#!/bin/bash --

x=`lsof -Fp -i:1025`
kill -9 ${x##p}
Run Code Online (Sandbox Code Playgroud)

应该做。第 3 行lsof使用-F选项运行以获取 pid,并带有前导p. 下一行从 的输出中删除前导 plsof并将结果用作kill命令中的 pid 。

编辑:在某些时候lsof被修改,因此f无论您是否要求,始终输出以 an 开头的文件描述符(这对我来说毫无意义,但我知道什么)。虽然您可以将 a| grep '^p'放在后引号中,但更简单的方法是使用该-t选项,如下面 fabianopinto 的回答所述。