I have a script as follows, and I am trying to run it as a root cron job. The script starts mycommand, which in turn starts another process. When a condition is met, I would like the script to kill mycommand and its child process before exiting. Now, this seems to work at the terminal, the child processes end when the condition is met. But when the script is started as a root cron job, mycommand continues to run until I kill it manually. What am I doing wrong?
#!/bin/bash
# function to trap and clean exit
function clean_exit
{
PGID=`ps xao pgid,command,pid | grep 'mycommand'| sed 's/ .*//'`
kill -9 -$PGID
echo "process group killed: "$PGID
}
trap clean_exit SIGINT SIGTERM EXIT
sudo mycommand $1 > output.txt &
while sleep 1; do
# check output.txt every second
if [ condition met]; then
exit 1;
fi;
done
crontab line is as follows:
30 10 * * * bash path/to/myscript.sh
exec
, oreval $variable
; and the test condition isif [[ -z $(ps -aux | grep "$variable" | sed '$ d') ]]
... – pa4080 Jan 19 '19 at 15:30clean_exit
function works at all - on my 16.04 system, all the lines fromps xao pgid,command,pid
start with a space - sosed 's/ .*//'
returns a bunch of empty lines – steeldriver Jan 19 '19 at 17:16ps xao
, so i didn't realise that pgids with fewer digits (e.g. 5000) than the higher pgids (e.g. 12345) have leading space(s). I have now changed thatsed
toawk '{print $1}'
and it works as it should in crontab too. I didn't catch it at the terminal because the pgids didn't have leading spaces during testing. Could you post your comment as an answer please, so that I can accept it? Thanks. – srao Jan 19 '19 at 20:44grep 'mycommand'
togrep '[m]ycommand'
to exclude thegrep
process from the results. – dessert Jan 20 '19 at 08:30