0

We see the running PHP scripts with this command below on terminal:

echo 'User | ProcID | CPU | MEM | ----------------------- START | ELAPSED ---------- COMMAND'; 
ps aux --forest | grep php;

I would like to be email alerted when there is more than one copy of a file running at the same time. Even kill the earlier process maybe automatically!

This happens on cron jobs, when one script is stuck somehow and there comes the the next cycled run time for the cron and you have a stuck (or incomplete, slow script) continuing to run and a new instance of the same script running at the same time.

You may offer a better BASH solution (other than modifying the PHP script).

See image attached for example problem script:

\_ php -f /var/webserver/public_html/cron/scheduled_job_1.php
(process id: 3824)

BASH Alert Script for Ubuntu 16.04.

dessert
  • 40,956
Tarik
  • 215

1 Answers1

3

The easiest way to ensure you have no two instances of your PHP script running would be IMHO to write a tiny wrapper script in Bash that kills any currently running instances of your exact command before running it.

You can then execute this wrapper script in your cronjob instead of the actual PHP command.

Possible wrapper implementation:

#!/bin/bash

my_command='php -f /var/webserver/public_html/cron/scheduled_job_1.php'

# kill processes with the exact command line as above, if any are running
if pkill -fx "$my_command" ; then
    # You can do something here, which runs only if a process was killed.
    # The command below would just echo a warning to the terminal (not visible as a cronjob)
    echo "$(date) - WARNING: Previous instance of '$my_command' was killed."
fi

# (re)run the command
$my_command

Or a generic wrapper that expects the command to run as argument.

#!/bin/bash
# This script expects a command as argument(s), like e.g. "my_wrapper sleep 60"

# kill processes with the given command line, if any are running
if pkill -fx "$*" ; then
    # You can do something here, which runs only if a process was killed.
    # The command below would just echo a warning to the terminal (not visible as a cronjob)
    echo "$(date) - WARNING: Previous instance of '$*' was killed."
fi

# (re)run the command
"$@"

If you save it e.g. as /usr/local/bin/my_wrapper, you can call it like

my_wrapper php -f /var/webserver/public_html/cron/scheduled_job_1.php
Byte Commander
  • 110,243