0

I created a php file I want to run all the time. I then created a basic wrapper I want CRON to run to insure the script is still running - and restart it if needed.

My crontab -e entry is like this:

20 * * * * /var/www/bot/cron.php

The contents of cron.php look like this.

#!/usr/bin/php
<?php
@exec ('ps aux | grep loop', $output, $ret_var);

$running = false;
foreach ($output as $line)
{
    if (strpos($line, 'bot.php') !== false)
    {
        $running = true;
        break;
    }
}

if (! $running)
{
    @exec('/usr/bin/nohup php ' . __DIR__ . '/bot.php >/var/log/bot_out 2>&1 &');
}

die();

However, I'm having trouble getting this working. Is there something I'm missing?

I'm not getting anything on any error log, and /var/log/bot_out does show some runtime errors so I know PHP must be called.

PHP Warning:  Module 'apc' already loaded in Unknown on line 0
PHP Warning:  Module 'suhosin' already loaded in Unknown on line 0
8
  • This really seems like it should be something that's handled in a bash script, not a PHP script. Have it check if ps aux | grep -i loop | grep -i bot.php is a zero length string. If it is, launch the bot script, otherwise do nothing. Secondly, I think that cron line should read: 20 * * * * php /var/www/bot/cron.php. Commented Oct 2, 2012 at 15:54
  • What are the permissions on the file? How do those permissions match up with those you are executing cron as? Is /usr/bin/php the correct path to your PHP CLI executable? Commented Oct 2, 2012 at 15:54
  • @GigaWatt, my bash scripting is weak in this area, do you have an example script? Commented Oct 2, 2012 at 15:55
  • 1
    Give something like this a shot: if [ -z $(ps aux | grep -i loop | grep -i bot.php) ]; then php /some/dir/bot.php; fi Commented Oct 2, 2012 at 15:56
  • @Gigawatt It doesn't need php in the cron command as he is using a shebang to identify the path to the PHP executable. Commented Oct 2, 2012 at 15:56

1 Answer 1

1
20 * * * * /var/www/bot/cron.sh

then contents of cron.sh

#!/bin/bash
KP=$(pgrep -P 1 -f bot.php)
if [ "X$KP" = "X" ]
  then
    /usr/bin/nohup php PATH_TO_YOUR_SCRIPT/bot.php 
fi
Sign up to request clarification or add additional context in comments.

2 Comments

Works, but /usr/bin/nohup: ignoring input and appending output to '/home/user/nohup.out' Any way to log (or ignore) output?
Append a 2>/dev/null after the command. It'll dump STDERR into the abyss.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.