PHP collaboration: concurrent shell_exec

  Asynchronous, coroutine, php, socket, swoole

It is often used in PHP programsshell_execExecute some commands while ordinary onesshell_execIs blocked, if the command execution time is too long, it may cause the process to be completely stuck.
InSwoole4It can be used in coordination environment.Co::execExecute many commands concurrently.

This article is based onSwoole-4.2.9AndPHP-7.2.9Version

Synergetic example

<?  php
 $c = 10;
 while($c--) {
 go(function () {
 //sleep 5 is used here to simulate a very long command
 co::exec("sleep 5");

Return value

Co::execAfter the execution is completed, the suspended coordination process will be resumed, and the output of the command and the exit status code will be returned.

var_dump(co::exec("sleep 5"));

Concorde result

htf@htf-ThinkPad-T470p:~/workspace/debug$ time php  t.php
 real    0m5.089s
 user    0m0.067s
 sys    0m0.038s

Only used5 seconds, the program ran out.

Let’s try PHP’s shell_exec.

Blocking code

<?  php
 $c = 10;
 while($c--) {
 //sleep 5 is used here to simulate a very long command
 shell_exec("sleep 5");

UsenohupOr&The result and output of the command execution cannot be obtained when it is transferred to background execution. This article will not discuss this in depth.

Blocking result

htf@htf-ThinkPad-T470p:~/workspace/debug$ time php  s.php
 real    0m50.119s
 user    0m0.066s
 sys    0m0.058s

You can see that the blocked version cost50 secondsJust finished.Swoole4The coordination provided is a sharp tool for concurrent programming. Concorde can be used in many places in the work to realize concurrent programs and greatly improve program performance.