#!/bin/bash
gearcmd --name oplog-dump --cmd /usr/local/bin/oplogdump --host $GEARMAN_HOST --port $GEARMAN_PORT &
pid=$!
# When we get a SIGTERM kill the child process and call wait. Note that we need wait both here
# and the line below because of the semantics of the kill syscall. As I understand it, wait returns
# the next time the state of the child process changes. Receiving a SIGTERM qualifies as a change
# of state, so if we don't have a wait after `kill $pid` then we will complete the trap handler
# and our call to `wait` below will complete. By calling `wait` after we kill the subprocess we wait
# for the next process state change which is the actual process termination.
trap "kill $pid && wait" SIGTERM SIGINT
# Wait so that this script keeps running
wait

#!/bin/bash
gearcmd --name oplog-dump --cmd /usr/local/bin/oplogdump --host $GEARMAN_HOST --port $GEARMAN_PORT &
pid=$!
# When we get a SIGTERM, forward it to the child process and call wait. Note that we wait both in here
# and below (on line 10) because when bash gets a SIGTERM bash appears to cancel the currently running
# command, call the trap handler, and then resume the script on the line after the line it was previously
# running. That means that without waiting in the trap we could exit the script before gearcmd actually exits.
trap "kill $pid && wait" SIGTERM SIGINT
# Wait so that this script keeps running
wait

Fix explanation of sigterm handling in bash
Fix explanation of sigterm handling in bash

Based on my current best understanding of the issue.
