3

I've got a python script thats called twice a day via a CRON job to trigger an alarm that runs in a loop, and is terminated by pressing a physical button and calling a destroy function when that button is pressed.

So far so good.

Now, I'd like to check via PHP if that script is running - so before the button is pressed but after it's called via CRON.

How can I do this?

Based on this question - I've tried the following:

exec("jobs", $pids);
if(!empty($pids)) {
    print_r($pids);
}

But it doesn't seem to be returning any value. Calling jobs from the terminal works as expected and lists the job as running when invoking the script directly using python3 alarm.py &.

Using exec("ps -A | grep -i $processName | grep -v grep", $pids); I feel won't work since the process ID can change and can not be known until the script is running.

Michał
  • 868
  • 1
  • 10
  • 36

1 Answers1

3

Use pgrep for this:

pgrep -f 'python scriptname.py ...'

-f can be used specify the full command line of the python process to avoid collision with multiple python processes running in parallel.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Thanks! When I call this using PHP's exec function I don't get any result. Pasting `pgrep -f python /home/pi/Projects/sound.py` directly into the terminal I get the following error: "pgrep: only one pattern can be provided". Typing in `pgrep -f python` in the terminal correctly returns the PID of the script, but since the PID is unknown until the script is run I'm at a bit of a loss... – Michał Jul 25 '17 at 17:43
  • You need to quote the path. Sorry. updated my answer – hek2mgl Jul 25 '17 at 18:06