1

I'm trying to get the PID of tcpdump which is part of a while loop. Example:

tcpdump -x -q -l -i $IFACE port $PORT | while read buffer; do
   # process, if something received from tcpdump. Otherwise wait
done

$! within the while loop will not provide the PID of tcpdump.

How to get the PID of tcpdump in this construct?

sourcejedi
  • 50,249
autio
  • 11
  • Why do you need the PID? What are you trying to achieve here? – Bex Aug 02 '17 at 08:42
  • Well, tcpdump is listening on a specific interface and port on wake-on-lan request. That's fine so far and is working as needed. But if I kill the process of my script with kill -9 PID_of_script, tcpdump hangs independently in the process list. So, I assume tcpdump is still listening. For that reason I have a trap installed which will kill the tcpdump. But for that I need the PID of tcpdump. For sure I could get the PID by using ps - ef|grep tcpdump, but I think there is a more elegant way to do it. – autio Aug 02 '17 at 08:51
  • see also https://stackoverflow.com/questions/1652680/how-to-get-the-pid-of-a-process-that-is-piped-to-another-process-in-bash and https://stackoverflow.com/questions/3345460/how-to-get-the-pid-of-a-process-in-a-pipeline – cas Aug 02 '17 at 08:56

1 Answers1

0

If you want to run the command and exit it conditionally later, you can run it in a separate shell:

bash -c 'tcpdump -xli eth0 | while read buffer; do
      if true; then exit; fi
    done'
Bex
  • 768