PHP: calling process to run in the back-end
Blogs20122012-09-17
PHP: calling process to run in the backend
Sometimes we need PHP to call server-side scripts. e.g., using PHP to call Perlâs cgi or bash script to do some server-side stuff. There are 2 possible issues:
(1) calling a script without waiting
Here is my way to implement the without waiting calling:
<php
$key = trim($_POST['key']);
if (!empty($key)) {
exec("/cgi-bin/search.pl '" . $key ."' >/dev/null 2>&1 &");
// or:
// exec("nohup /cgi-bin/search.pl '" . $key ."' >/dev/null 2>&1 &");
}By using â&â at the end of the command, Linux will fork a new child process to execute the Perl script (.pl), thus, seperate it from the original php script.
The benefit is that the php script doesnât need to wait for processingâs return, no waiting time, just dispatching a task to run back-end. This is very useful in the case of using webpage-form to trigger a âbackupâ process or âsearchingâ process. User clicks a button, close the page, and just let it do!
(2) call a script and wait for return result.
How about calling a process with return value? Here is the way:
<php
system("/bin/process.sh >/dev/null 2>&1", $retval);
if ($retval == 0) echo 'success';
else echo 'failue';
?>Notice: here is no â&â at the end of the command, and we use âsystemâ command instead of âexecâ because it comes with return value, not fork a child-process and let it go.
After the calling, immediately we judge the return value, here is $retval, to decide next step to go.
