1

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 
srao
  • 111
  • Hello, in this answer I've used similar approach, but the whole command is stored as value of variable and then it is executed by using exec, or eval $variable; and the test condition is if [[ -z $(ps -aux | grep "$variable" | sed '$ d') ]]... – pa4080 Jan 19 '19 at 15:30
  • 3
    I'm curious how your clean_exit function works at all - on my 16.04 system, all the lines from ps xao pgid,command,pid start with a space - so sed 's/ .*//' returns a bunch of empty lines – steeldriver Jan 19 '19 at 17:16
  • @steeldriver That's a good catch! It looks like pgids are right-aligned by ps 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 that sed to awk '{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:44
  • 1
    Change grep 'mycommand' to grep '[m]ycommand' to exclude the grep process from the results. – dessert Jan 20 '19 at 08:30

0 Answers0