简体   繁体   中英

Why do processes started from a bash script used as monit service persist after the script terminates?

I have a bash script that I've set up as a monit service. The script ends with a long-running call to tail that pipes its output to nc to be sent to an external server.

The issue I'm having is that when I stop the service using monit, the process for the bash script dies, but the process for the tail call made by that script persists. I've showed an example of this behavior below.

$ sudo monit start service
$ ps aux | grep -E 'service|tail'
root     26215  0.0  0.0  17876   464 ?        S    18:31   0:00 /bin/bash -x /path/to/service.sh &>/var/log/service.log
root     26216  0.0  0.0   4344   352 ?        S    18:31   0:00 tail -q -n 0 -f /var/log/app.log /var/log/db.log /var/log/mail.log
root     26217  0.0  0.1  20736  1060 ?        S    18:31   0:00 nc server.foo.com 1234
$ sudo cat /var/run/service.pid
26215
$ sudo monit stop service
$ ps aux | grep -E 'service|tail'
root     26216  0.0  0.0   4344   352 ?        S    18:31   0:00 tail -q -n 0 -f /var/log/app.log /var/log/db.log /var/log/mail.log
root     26217  0.0  0.1  20736  1060 ?        S    18:31   0:00 nc server.foo.com 1234

I've tried making the tail call in a few different ways:

1) in the foreground, outputting the bash script PID to the PID file

echo "$$" > $PID_FILE
tail -q -n 0 -f $args | nc server.foo.com 1234

2) in the background without using a subshell, outputting what should be the last backgrounded process PID to the PID file

{ tail -q -n 0 -f $args | nc server.foo.com 1234; } &
echo "$!" > $PID_FILE

3) in the background using a subshell, outputting what should be the subshell PID to the PID file

( echo $BASHPID > $PID_FILE; tail -q -n 0 -f $args | nc server.foo.com 1234 ) &

Oddly, all these approaches appear to result in the behavior shown above: the bash script PID is always used, the bash script process terminates when monit stops the service, the tail process does not.

I want to know why this happens and how to kill off any processes invoked by the bash script when the associated service is terminated by monit.

尝试:

bash -c "tail -q -n 0 -f $args | nc server.foo.com 1234"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM