Asynchronous Function Call in PHP

前端 未结 7 1523
逝去的感伤
逝去的感伤 2020-11-30 20:54

I am working on an a PHP web application and i need to perform some network operations in the request like fetching someone from remote server based on user\'s request.

7条回答
  •  日久生厌
    2020-11-30 21:51

    One way is to use pcntl_fork() in a recursive function.

    function networkCall(){
      $data = processGETandPOST();
      $response = makeNetworkCall($data);
      processNetworkResponse($response);
      return true;
    }
    
    function runAsync($times){
      $pid = pcntl_fork();
      if ($pid == -1) {
        die('could not fork');
      } else if ($pid) {
        // we are the parent
        $times -= 1;
        if($times>0)
          runAsync($times);
        pcntl_wait($status); //Protect against Zombie children
      } else {
        // we are the child
        networkCall();
        posix_kill(getmypid(), SIGKILL);
      }
    }
    
    runAsync(3);
    

    One thing about pcntl_fork() is that when running the script by way of Apache, it doesn't work (it's not supported by Apache). So, one way to resolve that issue is to run the script using the php cli, like: exec('php fork.php',$output); from another file. To do this you'll have two files: one that's loaded by Apache and one that's run with exec() from inside the file loaded by Apache like this:

    apacheLoadedFile.php

    exec('php fork.php',$output);
    

    fork.php

    function networkCall(){
      $data = processGETandPOST();
      $response = makeNetworkCall($data);
      processNetworkResponse($response);
      return true;
    }
    
    function runAsync($times){
      $pid = pcntl_fork();
      if ($pid == -1) {
        die('could not fork');
      } else if ($pid) {
        // we are the parent
        $times -= 1;
        if($times>0)
          runAsync($times);
        pcntl_wait($status); //Protect against Zombie children
      } else {
        // we are the child
        networkCall();
        posix_kill(getmypid(), SIGKILL);
      }
    }
    
    runAsync(3);
    

提交回复
热议问题