IMHO the best way to do this is to have the running script periodically check for some flag that is set via the other script. One easy way to do that is to have the running script check for the existence of a file (
stop-script, for example) which normally doesn't exist.
Then all you need to do in the script that is run when the
Stop Button is pressed is to create (or
touch) the file
The running script should then delete the
stop-script file just before it exits setting up for the next execution of the running script.
Here's what I envision in pseudo code (using python indentation for blocks):
while( TRUE )
-- code to check sensor
if exists '/path/to/stop-script'
continue # exit while loop
sleep(5) # sleep for 5 seconds
print 'stop-script file detected'
delete file '/path/to/stop-script'
print 'stop-script file deleted - we will now exit'
Something like that.
Update: Answer to 2nd problem, namely web page hangs when running main script
Your second issue is that when in PHP you run
exec('sudo python /var/www/SensorON.py'); , PHP will wait for the command to terminate, which in your case doesn't happen until later. You need to make this command run "asynchronously", see this for more detail, but effectively you need the following in your PHP web page:
exec('sudo python /var/www/SensorON.py > /dev/null 2>/dev/null &');
exec('sudo touch /var/www/SensorOFF.py');
> /dev/null 2>/dev/null & to the command string redirects the output of the Python program to
/dev/null (the bit bucket) and most importantly the final "
&" character causes Python to run as a separate process and return is immediately returned to PHP allowing your web page to complete.