4

For example:

//test.php
#! /usr/local/php/bin/php
<?php
exec('nohup ./loop.php > loop.out');
echo 'I am a superman!';

//loop.php
#! /usr/local/php/bin/php
<?php
$count = 0;
while (true) {
    echo "Loop count:{$count}\n";
    $count++;
}

When I run ./test.php I can not get the output 'I am a superman!', as you know loop.php is an endless loop, test.php is interrupted by loop.php, so how can I get the output? Any help is appreciated.

hakre
  • 193,403
  • 52
  • 435
  • 836
Joel
  • 111
  • 7

3 Answers3

3

There is a bunch of ways you can achieve this:

Running background process using &:

exec('nohup ./loop.php > loop.out 2>&1 &');

Using pcntl_fork and running your process from child:

 $pid = pcntl_fork();
 switch ($pid){
   case -1:
     die('Fork failed');
     break;
   case 0:
     exec('nohup ./loop.php > loop.out');
     exit();
   default:
     break;
 }
 echo "I'm not really a superman, just a parent process';

There is more ways to do this, just lurk into PHP documentation and questions in here...

Juicy Scripter
  • 25,778
  • 6
  • 72
  • 93
2

To do asynchronous processes in PHP you would want to use something like Gearman or beanstalkd

wyqydsyq
  • 1,992
  • 1
  • 20
  • 28
  • 1
    +1 I'm a fan of beanstalkd myself, but the core message is the same: queue it. Among other things, this lets you easily control the maximum number of simultaneous jobs -- don't run more queue consumers than you can handle. – Frank Farmer Jan 19 '12 at 07:53
  • I've never heard about beanstalkd, it looks really nice! Updated answer to include a reference to it – wyqydsyq Jan 19 '12 at 23:52
0

It's never a good idea to have a "never ending" loop running. If you need to have a particular task run frequently, consider using Cron Jobs, provided by the Server OS and not actually part of PHP.

Also, if a section of your PHP code needs a lot of time to execute, you should change your design approach to queue the Job on Database and have an external Job Scheduler process it.

Look at this post for more details.

Community
  • 1
  • 1
Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
  • Cron jobs should be a good way that process tasks frequently, but I just want to run an external program without waiting for it finish. In addition, I want to start the external program by php script logic not a fixed-frequency task. – Joel Jan 19 '12 at 06:56