11

I think there are tons of similar posts but I haven't yet found a solution after searching around.

Basically, I'm trying to run two scripts in the background. When I run them in the commandline, I see after calling my first script:

/usr/bin/nohup php script.php > nohupoutput.log & echo $!

I've tried ...script.php > /dev/null & with the same result. I get:

/usr/bin/nohup: ignoring input and redirecting stderr to stdout

which I ignore and run the second one. I noticed that it seemed to be hanging there, and pressing Enter brought me back to machine:~folder>

/usr/bin/nohup php script2.php > nohupoutput.log & echo $!

Both scripts work. I tried to then convert this to a shell_exec command and nothing seems to work. I suspect that the ignoring input bit is causing difficulties, but I'm not sure. Regardless, the following does not work. It just hangs in the browser:

$output = shell_exec('/usr/bin/nohup php script.php > /dev/null &');
$output = shell_exec('/usr/bin/nohup php script2.php > /dev/null &');
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Rio
  • 14,182
  • 21
  • 67
  • 107

4 Answers4

12

Try:

$output = shell_exec('/usr/bin/nohup php script.php >/dev/null 2>&1 &');

Or:

exec('/usr/bin/nohup php script.php >/dev/null 2>&1 &');
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
2

This shoul work:

shell_exec('nohup /usr/bin/php path/to/script.php > output.txt &');
Jan
  • 21
  • 1
2
<?php
function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r")); 
    }
    else {
        exec($cmd . " > /dev/null &");  
    }
}

// take note: to get your PHP_PATH, try looking at your phpinfo :)
echo execInBackground("/usr/local/php53/bin/php 'example2.php'");
?>
Alexis Tyler
  • 1,394
  • 6
  • 30
  • 48
i am ArbZ
  • 69
  • 3
  • 1
    `popen('nohup ... &', 'r')` is the only method that is working for me in OS X as well as Heroku. A ton of other solutions for running detached background processes incl. Symfony, Cocur, et al failed (either blocked execution or would die when parent dies). – Ezekiel Victor Mar 20 '16 at 03:10
0

First put your php command in a shell file script, e.g. myscript.sh:

#!/bin/bash
# myscript.sh file
php script.php

Run nohup with myscript.sh:

sudo nohup ./myscript.sh &

Verify with ps:

ps aux | grep myscript.sh
renedet
  • 287
  • 3
  • 12