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.

3 Answers 3

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...

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

+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.
I've never heard about beanstalkd, it looks really nice! Updated answer to include a reference to it
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.