How to get the pid of command running with sudo How to get the pid of command running with sudo unix unix

How to get the pid of command running with sudo


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 CMD16772 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] 37201tcpdump: listening on en3, link-type EN10MB (Ethernet), capture size 65535 bytes$ sudo kill `cat /tmp/tcpdump.pid`6212 packets captured6243 packets received by filter0 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