0

I have a problem to pass signals like SIGKILL, SIGINT, SIGTERP to bash script which use tcpdump.

The main issue - how to kill tcpdump process (child) if homeone kill the main script.

I have the following script (part):


#for log
function log {
    echo "$CURRENT_DATE_TIME $1" >> "${LOG_DIR}/${MAIN_LOG_FILE}"
    echo "$1"
}

#to start tcpdump
function start_tcpdump {
    ${TCPDUMP} ${TCPDUMP_ARGS} ${TCPDUMP_LOG_FILE} ${TCPDUMP_SMPP_PDU} &
    TCPDUMP_PID=$!
    log "Start tcpdump PID: ${TCPDUMP_PID}"
    sleep 60

}

#to stop tcpdump
function stop_tcpdump {
    kill -s 2 ${TCPDUMP_PID}
    log "Stop tcpdump PID ${TCPDUMP_PID}"
    TCPDUMP_PID=0
}

#check if process exists
function check_tcpdump {
        if [[ ${TCPDUMP_PID} -ne 0 ]] && [[ -e /proc/${TCPDUMP_PID} ]] && kill -s 0 "${TCPDUMP_PID}" 2>/dev/null
        then
            log "Checking tcpdump. Already started PID ${TCPDUMP_PID}"
            return 1
        else
            log "Checking tcpdump. Not started"
            return 0
        fi
#       [[ ${TCPDUMP_PID} -ne 0 ]] && [[ -e /proc/${TCPDUMP_PID} ]] && kill -s 0 "${TCPDUMP_PID}" 2>/dev/null
}

#main function here
function main {
    log "#####INIT#####"
    start_tcpdump

    trap stop_tcpdump SIGINT SIGKILL SIGTERM SIGSTOP
    check_tcpdump
    stop_tcpdump
}

main

But if someone forget and kill sript:

$ sh ./gms_trace_smpp.sh

$ kill $pid

process which manage tcp dump still exists.

I'd like to call stop_tcpdump function and kill child tcpdump process if script gets one of the signals (SIGINT SIGKILL SIGTERM SIGSTOP).

And have made it using trap:

trap stop_tcpdump SIGINT SIGKILL SIGTERM SIGSTOP

But it doesn't work.

Does someone have any idea how to handle signal and kill child process (tcpdump) when someone kill the main script?

  • From `man trap` "Implementations may permit names with the SIG prefix" - but they may not. Remove the SIG prefixes from trap specification. | If you want to exit after receiving the signal, call `exit` in the trap handler. – KamilCuk Mar 28 '19 at 08:36
  • You should have a look at [What does `set -o errtrace` do in a shell script?](https://stackoverflow.com/q/25378845/5291015) – Inian Mar 28 '19 at 09:16
  • 1
    SIGKILL and SIGSTOP can't be trapped! – Wiimm Mar 28 '19 at 10:08
  • If SIGKILL and SIGSTOP can't be trapped, how can I also stop tcpdump process in script if someone kill this script? Maybe you have an idea. – Vladimir Len Mar 28 '19 at 12:18

1 Answers1

0

Some signals cannot normally be blocked. While there are ways to make a process unkillable, it's tricky, a bad idea, and probably not helpful.

One simple option is to add an at job to perform cleanup if it detects the script has exited (or it could always do the check_tcpdump and stop_tcpdump parts).

Another more complicated option is to intertwine the script with another - they can monitor each other and perform cleanup when either one exits (cf. Robin Hood and Friar Tuck)

jhnc
  • 11,310
  • 1
  • 9
  • 26