views:

2353

answers:

7

Hi,

I have this process intensive task that i would like to run in the background.

The user clicks on a page the PHP script runs and finally based on some conditions if required then it has to run a shell script EG: shell_exec('php measurePerformance.php 47 844 [email protected]');

Currently I use shell_exec BUT this requires the script to wait for an output. Is there anyway to execute the command I want and DO NOT wait for it to complete??

Thanks

+1  A: 

If it's off of a web page, I recommend generating a signal of some kind (dropping a file in a directory, perhaps) and having a cron job pick up the work that needs to be done. Otherwise, we're likely to get into the territory of using pcntl_fork() and exec() from inside an Apache process, and that's just bad mojo.

chaos
+12  A: 

How about adding.

"> /dev/null 2>/dev/null &"

shell_exec('php measurePerformance.php 47 844 [email protected] > /dev/null 2>/dev/null &');

Note this also gets rid of the stdio and stderr.

jitter
It works perfectly. Are there any problems / side effects of using this??
ToughPal
No. No side effects. If you sometime decide you want the stdio or stderr output of your process consider http://stackoverflow.com/questions/45953/php-execute-a-background-process/45966#45966
jitter
Question: That's just discarding the output, right? Does PHP still wait for the process to finish before continuing execution, or does it fire and forget?
Alan Storm
Yes discards out. Yes fire and forget
jitter
+1  A: 

This will execute a command and disconnect from the running process. Of course, it can be any command you want. But for a test, you can create a php file with a sleep(20) command it.

exec("nohup /usr/bin/php -f sleep.php > /dev/null 2>&1 &");
Brent Baisley
A: 

You could always post over some AJAX to a page that calls the shell_exec().

zacharydanger
+2  A: 

Hi ToughPal,

That will work but you will have to be careful not to overload your server because it will create a new process every time you call this function which will run in background. If only one concurrent call at the same time then this workaround will do the job.

If not then I would advice to run a message queue like for instance beanstalkd/gearman/amazon sqs.

Alfred
A: 

Use php's POPEN command eg. pclose(popen("start c:\wamp\bin\php.exe c:\wamp\www\script.php","r")) .. this will create a child process and script will excute in background with out waiting for output ... enjoy !!!

A: 

to call another script without waiting on my windows 2003 I used this:

$commandString = "start /b c:\php\php.EXE C:\Inetpub\wwwroot\mysite.com\phpforktest.php --passmsg=$testmsg"; pclose(popen($commandString, 'r'));

This only works AFTER giving changing permissions on cmd.exe - add Read and Execute for IUSR_YOURMACHINE (I also set write to Deny)