Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the pid of command running with sudo

I am trying to get the pid of this command.

sudo -b tcpdump -i eth0 port 80 -w eth0.pcap
like image 818
user87005 Avatar asked Feb 16 '12 17:02

user87005


1 Answers

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.

like image 114
Chris Dodd Avatar answered Sep 24 '22 11:09

Chris Dodd