I want to start a new instance of my python script when it reaches a specified time during the hour and kill the current instance. The python script starts automatically with boot using a crontab. An infinite while loop reads data. If there is data incoming between minute 59 second 30 and minute 59 second 59, the file gets closed and I want the script to start a new instance of itself with a new process ID and kill the old process. At the moment I am doing this by using
subprocess.call(['python', '/home/pi/script.py'])
sys.exit(1)
That starts a new instance of the python script, but the old one is still visible and (it seems) active when I check the processes with top
.
Is there a better way to let the program start and kill itself inside the python script?
Another approach using a bash script called by the python script:
#!/bin/sh
PID=`ps -eaf | grep python | grep -v grep | awk '{print $2}'`
if [[ "" != "$PID" ]]; then
echo "killing $PID"
kill -9 $PID
sleep 1
sudo python /home/pi/readserial_V4_RP.py &
exit 1
fi
But that can't work because the python script end, before the bash script can kill it. I could start the python script without killing python
processes, but how can I be sure that no python script is running, before I start the new instance of the python script.
because I have the feeling, when I have more than one same python scripts running, that the first one that was started is doing all the "work" and the others are just in idle...