简体   繁体   中英

How to get the pid of command running with sudo

我想要得到这个命令的pid。

sudo -b tcpdump -i eth0 port 80 -w eth0.pcap

You can use $! to get the pid of the last background process (which will be the sudo in this case), and ps --ppid to find out about its children. So for example:

$ sudo tcpdump -i eth0 port 80 -w eth0.pcap &
$ ps --ppid $! -o pid=
16772
$ ps --pid 16772
  PID TTY          TIME CMD
16772 pts/3    00:00:00 tcpdump

If you're doing this in a script, you might want to use a sleep 1 between the sudo and ps 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.

Here's one way to do it:

sudo -u username sh -c "echo \$\$ > /tmp/my_pid/file; exec my_command" &

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 -u root sh -c "echo \$\$ > /tmp/tcpdump.pid; exec tcpdump -i en3 -w eth0.pcap" &
[1] 37201
tcpdump: listening on en3, link-type EN10MB (Ethernet), capture size 65535 bytes
$ sudo kill `cat /tmp/tcpdump.pid`
6212 packets captured
6243 packets received by filter
0 packets dropped by kernel
[1]+  Done                    sudo -u root sh -c "echo \$\$ > /tmp/tcpdump.pid; exec tcpdump -i en3 -w eth0.pcap"
$

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

11803

I could kill the program from awk as well by piping a kill command to bash

ps aux | awk '/gvim/ {print "sudo kill -9 "$2}' | bash

The -o option to ps 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:

ps -eo pid,command,lstart --sort lstart | grep 'sudo -b tcpdump' | tail -1

You don't even need to tell ps to display the field you want to sort by. man ps for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM