Search code examples
linuxshelltcpdumpnohup

Why doesn't tcpdump run in background?


I logged in a virtual machine via ssh and I tried to run a script in background, the script is shown below:

#!/bin/bash
APP_NAME=`basename $0`
CFG_FILE=$1
. $CFG_FILE #just some variables
CMD=$2
PID_FILE="$PIDS_DIR/$APP_NAME.pid"
CUR_LOG_DIR=$LOGS_RUNNING

echo $$ > $PID_FILE

#Main script code

#This script shall be called using the following syntax
# $ nohup script_name output_dir &

TIMESTAMP=`date +"%Y%m%d%H%M%S"`

CAP_INTERFACE="eth0"

/usr/sbin/tcpdump -nei $CAP_INTERFACE -s 65535 -w file_result

rm $PID_FILE

The result should be tcpdump running in background, redirecting the command result to file_result.

The script is called with:

nohup $SCRIPT_NAME $CFG_FILE start &

And It is stopped calling the STOP_SCRIPT:

##STOP_SCRIPT
PID_FILE="$PIDS_DIR/$APP_NAME.pid"

if [ -f $PID_FILE ]
then
  PID=`cat $PID_FILE`

  # send SIGTERM to kill all children of $PID
  pkill -TERM -P $PID
fi

When I check the file_result, after running the stop script, It is empty.

What is happening? How can I solve it?

I found this link: https://it.toolbox.com/question/launching-tcpdump-processes-in-background-using-ssh-060614

The author seems to have faced a similar issue. They debate about race conditions, but I didn't understand completely.


Solution

  • I'm not sure what you're trying to accomplish by having the startup script itself continue to run, but here's an approach that I think accomplishes what you're trying to do, namely start tcpdump and have it continue to run immune to hangups via nohup. I've simplified things a bit for illustrative purposes - feel free to add any variables back as you see fit, such as the nohup.out output directory, TIMESTAMP, etc.

    Script #1: tcpdump_start.sh

    #!/bin/sh
    rm -f nohup.out
    nohup /usr/sbin/tcpdump -ni eth0 -s 65535 -w file_result.pcap &
    
    # Write tcpdump's PID to a file
    echo $! > /var/run/tcpdump.pid
    

    Script #2: tcpdump_stop.sh

    #!/bin/sh
    if [ -f /var/run/tcpdump.pid ]
    then
            kill `cat /var/run/tcpdump.pid`
            echo tcpdump `cat /var/run/tcpdump.pid` killed.
            rm -f /var/run/tcpdump.pid
    else
            echo tcpdump not running.
    fi
    

    To start tcpdump, just run tcpdump_start.sh.
    To stop the tcpdump instance started with tcpdump_start.sh, just run tcpdump_stop.sh.

    The captured packets will be written to the file_result.pcap file, and yes, it's a pcap file, not a text file, so it helps to name it with the proper file extension. The tcpdump statistics will be written to the nohup.out file when tcpdump is terminated.