Adam Johnson
Adam Johnson

Reputation: 2216

PHP exec() not returning

I am writing a PHP script that will launch a program on the server.

I do so with:

exec('myAppName');

This line of code "works" in that it actually executes the program, however, I can't get the it to return (continue past) from this line.

It will just hang there, until I either manually close the program that was opened or the max_execution_time is exceeded.

Am I missing something obvious?

Upvotes: 0

Views: 2284

Answers (4)

user965927
user965927

Reputation: 35

If you want to execute a command in the background without having the script waiting for the result, you can do the following:

<?php
passthru("/usr/bin/php /path/to/script.php ".$argv_parameter." >> /path/to/log_file.log        2>&1 &");
?>

There are a few thing that are important here.

First of all: put the full path to the php binary, because this command will run under the apache user, and you will probably not have command alias like php set in that user.

Seccond: Note 2 things at the end of the command string: the '2>&1' and the '&'. The '2>&1' is for redirecting errors to the standard IO. And the most important thing is the '&' at the end of the command string, which tells the terminal not to wait for a response.

Third: Make sure you have 777 permissions on the 'log_file.log' file

Enjoy!

Upvotes: 0

Westie
Westie

Reputation: 457

To background a process in PHP, you'll need to do something like this:

function spawnBackgroundProcess($sProcessLine)
{
    $aPipes = array();

    $rProcess = proc_open($sProcessLine, array(), $aPipes);
    proc_close($rProcess);
}

Really that's abusing the proc_* family, but it's the best way sadly.

(Don't forget the &!)

Upvotes: 1

FreudianSlip
FreudianSlip

Reputation: 2920

You need to background it in order to continue with the rest of the php I believe.

In Unix/Linux, use the "&" character. ..

Hm or is that System that does that .. damn, cant remember now - will go read the manual again.

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

The manual for exec, while not being entirely clear on the matter of waiting for the launched program to exit, states the return value to be

Return values: The last line from the result of the command.

In other words, just as you're observing, in order to return the last line output, exec won't return until the launched program exits.

Upvotes: 1

Related Questions