The demon does not kill children who read from a named pipe
I wrote this bash daemon that monitors a named pipe, logs whatever it sees in a file named $LOG_FILE_BASENAME.$DATE
, and also creates a filtered version of it in $ACTIONABLE_LOG_FILE
:
while true
do
DATE=`date +%Y%m%d`
cat $NAMED_PIPE | tee -a "$LOG_FILE_BASENAME.$DATE" | grep -P -v "$EXCEPTIONS" >> "$ACTIONABLE_LOG_FILE"
done
pkill -P $$ # Here it where it should kill it children
exit 0
When the daemon starts up, this is what the process table looks like:
/bin/sh the_daemon.sh
\_ cat the_fifo_queue
\_ tee -a log_file.20150807
\_ grep -P -v "regexp" > filtered_log_file
The problem is that when I kill the daemon (SIGTERM) the cat, tee and grep processes that spawn the daemon are not collected by the parent. Instead, they become orphans and continue to wait for named pipe input.
As soon as the FIFO receives some input, they process that input as specified and die.
How can I make a demon kill my children to death? Why don't they die with help pkill -P $$
?
source to share
You want to set up a signal handler for your script that kills all members of its process group (its children) if the script itself receives a signal:
#!/bin/bash
function handle_sigterm()
{
pkill -P $$
exit 0
}
trap handle_sigterm SIGTERM
while true
do
DATE=`date +%Y%m%d`
cat $NAMED_PIPE | tee -a "$LOG_FILE_BASENAME.$DATE" | grep -P -v "$EXCEPTIONS" >> "$ACTIONABLE_LOG_FILE"
done
handle_sigterm
exit 0
Update:
As per pilot comment, replace
cat $NAMED_PIPE | tee -a "$LOG_FILE_BASENAME.$DATE" | grep -P -v "$EXCEPTIONS" >> "$ACTIONABLE_LOG_FILE"
by
cat $NAMED_PIPE | tee -a "$LOG_FILE_BASENAME.$DATE" | grep -P -v "$EXCEPTIONS" >> "$ACTIONABLE_LOG_FILE" &
wait $!
source to share