如何获取使用 sudo 运行的命令的 pid
我正在尝试获取该命令的 pid。
sudo -b tcpdump -i eth0 port 80 -w eth0.pcap
I am trying to get the pid of this command.
sudo -b tcpdump -i eth0 port 80 -w eth0.pcap
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
$!
获取最后一个后台进程的 pid(在本例中为 sudo),并使用ps --ppid
来了解其子进程。例如:如果您在脚本中执行此操作,您可能需要在
sudo
和ps
之间使用sleep 1
以确保让孩子开始。请注意,如果您确实必须对 sudo 使用
-b
标志,则这将不起作用,因为这将导致 sudo 进行额外的 fork 并立即退出,从而失去子级和父级之间的连接( tcpdump 命令将被重新设置为 init),这意味着您将无法简单地将子命令与任何其他类似命令区分开来。You can use
$!
to get the pid of the last background process (which will be the sudo in this case), andps --ppid
to find out about its children. So for example:If you're doing this in a script, you might want to use a
sleep 1
between thesudo
andps
to ensure that the child gets started.Note that if you really must use the
-b
flag to sudo, this won't work, as that will cause sudo to do an extra fork and immediately exit, losing the connection between child and parent (the tcpdump command will get reparented to init), which means you'll have no easy way of distinguishing the child from any other similar command.这是一种方法:
这里的其他答案依赖于 grep ps 输出。如果有多个 tcpdump 命令正在运行,您可能会意外地 grep 到错误的 pid。这会获取实际的 pid 并将其放入文件中。
下面是一个以 root 身份运行 tcpdump 的示例:
Here's one way to do it:
The other answers here rely on grepping ps output. If there's multiple tcpdump commands running, you may accidentally grep the wrong pid. This gets the actual pid and puts it in a file.
Here's an example running tcpdump as root:
为此,我将输入
sudo gvim &
ps aux | grep gvim
为我提供以下输出
root 11803 0.0 0.0 12064 2776 pts/3 T 12:17 0:00 sudo gvim
只获取我更喜欢使用 awk
辅助 | awk '/gvim/ {print $2}'
会简单地返回
来从 awk 终止程序
我也可以通过将终止命令传送到 bash ps aux | awk '/gvim/ {print "sudo Kill -9 "$2}' | bash
for this purpose I will enter
sudo gvim &
ps aux | grep gvim
supplies me with the following output
root 11803 0.0 0.0 12064 2776 pts/3 T 12:17 0:00 sudo gvim
to grab only the pID i prefer to use awk
ps aux | awk '/gvim/ {print $2}'
which would return simply
I could kill the program from
awk
as well by piping a kill command to bashps aux | awk '/gvim/ {print "sudo kill -9 "$2}' | bash
ps
的-o
选项允许您选择要显示的字段。在这些字段中,您可以显示累积 CPU 时间 (cputime
)、已用时间 (etime
) 和开始时间 (lstart
) 等内容。您还可以使用--sort
对字段进行排序。因此,您的解决方案可能是:您甚至不需要告诉
ps
显示您想要排序的字段。man ps
了解更多详细信息。The
-o
option tops
lets you choose what fields to display. Of those fields, you can show things like cumulative cpu time (cputime
), elapsed time (etime
), and start time (lstart
). You can also sort on a field using--sort
. So a solution for you could be:You don't even need to tell
ps
to display the field you want to sort by.man ps
for more details.