How can I execute an external program without interrupting a PHP script

For instance:

//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’t get the output β€œI'm superman!”, since you know that loop.php is an infinite loop, test.php is interrupted by loop.php, so how can I get the output? Any help is appreciated.

+4
source share
3 answers

There are several ways to achieve this:

Starting a background process with & :

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

Using pcntl_fork and starting your process from a 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 are more ways to do this, just have a look at the documentation and PHP questions in here ...

+3
source

For executing asynchronous processes in PHP you would like to use something like Gearman or beanstalkd

+2
source

It is never recommended to have a loop "infinite". If you need a particular task to be performed frequently, consider using the Cron jobs provided by the server OS, rather than actually part of PHP.

In addition, if part of your PHP code takes a long time to complete, you must change your design approach to queue a job in the database and run an external task scheduler.

See this article for more details.

0
source

Source: https://habr.com/ru/post/1391773/


All Articles