pythonRcpp
pythonRcpp

Reputation: 2146

Cronjob command starts 2 processes, for 1 python script

My crontab had the command:

50 08 * * 1-5 /home/MY_SCRIPT.py /home/arguments 2> /dev/null

59 23 * * 1-5 killall MY_SCRIPT.py

Which worked perfectly fine, but when I used to do

ps aux | grep SCRIPT

It showed:

myuser 13898 0.0 0.0 4444 648 ? Ss 08:50 0:00 /bin/sh -c /home/MY_SCRIPT.py /home/arguments 2> /dev/null

myuser 13900 0.0 0.0 25268 7384 ? S 08:50 0:00 /usr/bin/python /home/MY_SCRIPT.py /home/arguments

I made a change to my script and in order to get the new behaviour, I had to kill the currently running scripts and I used

kill 13898 13900

After that I used the same command (as in crontab)

/home/MY_SCRIPT.py /home/arguments 2> /dev/null

Everything looks good till here, but this time the killall MY_SCRIPT in the cronjob didnt work, it said could not find pid. And the script kept on running until I had to manually kill it.

Need to find out the reason for this behaviour:

  1. Why 2 processes from cronjob
  2. Is there something wrong the way I restrated the script
  3. How do I make sure that next time I restart the script, the cron should kill it for sure

OS:Linux Ubuntu

Upvotes: 1

Views: 2020

Answers (1)

konsolebox
konsolebox

Reputation: 75548

You're seeing two processes because crontab uses /bin/sh to summon your python script. So basically what happens is:

/bin/sh -c '/home/MY_SCRIPT.py /home/arguments 2> /dev/null'

And the process structure becomes

/bin/sh -> /usr/bin/python

Try this format instead:

50 08 * * 1-5 /bin/sh -c 'exec /home/MY_SCRIPT.py /home/arguments 2> /dev/null'

It may also be a good idea to specify the full path to killall. It's probably in /usr/bin. Verify it with which killall.

59 23 * * 1-5 /usr/bin/killall MY_SCRIPT.py 

Another more efficient way to do it is to save your process id somewhere:

50 08 * * 1-5 /bin/sh -c 'echo "$$" > /var/run/my_script.pid; exec /home/MY_SCRIPT.py /home/arguments 2> /dev/null'

And use a more efficient killer:

59 23 * * 1-5 /bin/sh -c 'read PID < /var/run/my_script.pid; kill "$PID"'

Upvotes: 1

Related Questions