Quantcast
Viewing latest article 1
Browse Latest Browse All 6

Answer by SensorSmith for Forward SIGTERM to child in Bash

Andreas Veithen points out that if you do not need to return from the call (like in the OP's example) simply calling through the exec command is sufficient (@Stuart P. Bentley's answer). Otherwise the "traditional" trap 'kill $CHILDPID' TERM (@cuonglm's answer) is a start, but the wait call actually returns after the trap handler runs which can still be before the child process actually exits. So an "extra" call to wait is advisable (@user1463361's answer).

While this is an improvement it still has a race condition which means that the process may never exit (unless the signaler retries sending the TERM signal). The window of vulnerability is between registering the trap handler and recording the child's PID.

The following eliminates that vulnerability (packaged in functions for reuse).

prep_term()
{
    unset term_child_pid
    unset term_kill_needed
    trap 'handle_term' TERM INT
}

handle_term()
{
    if [ "${term_child_pid}" ]; then
        kill -TERM "${term_child_pid}" 2>/dev/null
    else
        term_kill_needed="yes"
    fi
}

wait_term()
{
    term_child_pid=$!
    if [ "${term_kill_needed}" ]; then
        kill -TERM "${term_child_pid}" 2>/dev/null 
    fi
    wait ${term_child_pid}
    trap - TERM INT
    wait ${term_child_pid}
}

# EXAMPLE USAGE
prep_term
/bin/something &
wait_term

Viewing latest article 1
Browse Latest Browse All 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>