Why can't I interrupt (i.e. kill -2, not kill -9) tcpdump as shown in this script? The script runs, but tcpdump does not terminate and continues to run at the command line, even after printing some of its exit output.
(Note: this script requires sudo due to tcpdump and kill).
#!/bin/bash
#start a process in the background (it happens to be a TCP HTTP sniffer on the loopback interface, for my apache server):
tcpdump -i lo -w dump.pcap 'port 80' &
#.....other commands that send packets to tcpdump.....
#now interrupt the process. get its PID:
pid=$(ps -e | pgrep tcpdump)
echo $pid
#interrupt it:
kill -2 $pid 4 3 Answers
I found part of the answer on this Stack Overflow post.
To summarize, tcpdump was buffering its output before writing to the output file, and this caused issues when the script attempted to interrupt it. Adding the -U ("flush") option to tcpdump fixes this.
Also necessary were a sleep command immediately after issuing tcpdump to allow it to initialize, and also before killing it, to allow it to write to the file:
#!/bin/bash
#start a process in the background (it happens to be a TCP HTTP sniffer on the loopback interface, for my apache server):
tcpdump -U -i lo -w dump.pcap 'port 80' & sleep 5#.....other commands that send packets to tcpdump.....
#now interrupt the process. get its PID:
pid=$(ps -e | pgrep tcpdump)
echo $pid
#interrupt it: sleep 5kill -2 $pidFor reference, from man tcpdump, under the -U option:
If the -w option is specified, make the saved raw packet output ``packet-buffered''; i.e., as each packet is saved, it will be written to the output file, rather than being written only when the output buffer fills.
After this, the script worked fine.
until [ $x -gt 13 ];
do tcpdump -i $1 -w /home/paul/chanscan/chan-$x-$now.pcapng -e -s 0 subtype probe-req or subtype probe-resp -v & sleep 10;
sleep 2;Here is a direct kill in less code:
kill $(ps -e | pgrep tcpdump);As you can see the instead of other variables I just killed the process 2 seconds after the 10 second sleep. The script i did contains a 10 second scan for every channel between 1-13 this was for probe requests and responses so, importance on killing the tcpdump running process was critical to start the next scan.
I always give around 2 seconds for using kill or switching channels etc. the answers above are all as equally good just thought I would show you a simplified answer that meets all needs in less code. hope this helps someone out. :-)
You can enter the command below:
killall tcpdumpThis is relevant if you had a continuous tcpdump running and wanted to end that process. Nothing else is affected.
1