Shell_exec php with nohup
Asked Answered
U

4

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 &');
Unquote answered 8/2, 2011 at 5:14 Comment(0)
H
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 &');
Howsoever answered 8/2, 2011 at 7:20 Comment(2)
I'm getting a Ambiguous output redirect when I try both on the command line.Unquote
which os are you using, and php version? this is a odd one.Howsoever
C
2

This shoul work:

shell_exec('nohup /usr/bin/php path/to/script.php > output.txt &');
Crowther answered 28/11, 2013 at 15:42 Comment(0)
T
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'");
?>
Tradelast answered 14/5, 2014 at 0:23 Comment(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).Ragan
D
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
Dogs answered 10/12, 2021 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.