Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: exec() doesn't run in the background even with ">/dev/null 2>&1 &"

I'm calling this in my php script:

    exec("gutschein.php >/dev/null 2>&1 &");

Calling the script (generates a pdf and sends it away by e-mail) works, but the process is not running in the background (I checked it out with a sleep statement inside gutschein.php). The browser is hanging until execution of gutschein.php is finished.

I also checked out the following:

    exec("/usr/bin/php gutschein.php >/dev/null 2>&1 &");

or

shell_exec("/usr/bin/php gutschein.php >/dev/null 2>&1 &");

It doesn't change anything. The script is actually running on a linux server. Has anybody an idea what I'm doing wrong?

like image 448
cesare Avatar asked Sep 18 '12 12:09

cesare


4 Answers

    /**
     * @author Micheal Mouner
     * @param String $commandJob
     * @return Integer $pid
     */
    public function PsExec($commandJob)
    {
        $command = $commandJob . ' > /dev/null 2>&1 & echo $!';
        exec($command, $op);
        $pid = (int) $op[0];
        if ($pid != "")
            return $pid;
        return false;
    }

This worked for me .. check it

also, return processId of the background process

like image 64
Micheal Mouner Mikhail Youssif Avatar answered Nov 13 '22 14:11

Micheal Mouner Mikhail Youssif


Can you try one of the following 2 commands to run background jobs from PHP:

$out = shell_exec('nohup /usr/bin/php /path/to/gutschein.php >/dev/null 2>&1 &');

OR

$pid = pclose(popen('/usr/bin/php gutschein.php', 'r'));

It will execute the command in background and returns you the PID, which you can check using condition $pid > 0 to ensure it has worked.

like image 44
anubhava Avatar answered Oct 20 '22 00:10

anubhava


Try system and/or passthru. I've had issues with exec before because it halts trying to fill the return array with data until the process has finished.

These will both echo raw output so even if they work you may need to handle that with a discarded output buffer.

like image 4
Dave Avatar answered Nov 13 '22 14:11

Dave


All output must be redirected, else the script will hang as long as gutschein.php executes. Try

exec('/usr/bin/php gutschein.php &> /dev/null &');
like image 1
Martin Müller Avatar answered Nov 13 '22 14:11

Martin Müller