G
G
Grigory Vasilkov2017-03-21 10:04:07
PHP
Grigory Vasilkov, 2017-03-21 10:04:07

How to make an asynchronous call to a parser from PHP?

I'm catching deadlock..., why - apparently I don't understand something

// threads.php
  // dummy файл, чтобы загрузить процесс чем-нибудь, пока выполняется функция
  require_once 'functions.php';

  // EOF

// functions.php
  // файл-библиотека функций

  defined($var = '__APPDIR__') or define($var, dirname(__FILE__));
  
  // _doAsync
  // выполняет "асинхронную" команду
  if (!function_exists("_doAsync")):
    function _doAsync(Callable $async_func) {
      $path = realpath('threads.php');
      $spec = array(
        0 => array('pipe', 'r'),
        1 => array('pipe', 'w'),
        2 => array('pipe', 'r')
      );
      $pipes = array();
      $h = proc_open(sprintf('php %s', $path), $spec, $pipes, $cwd = __APPDIR__, $env = null);

      // start async
      $async_func();
      // end async

      $stdout = stream_get_contents($pipes[1]);
      fclose($pipes[0]);
      fclose($pipes[1]);
      fclose($pipes[2]);
      proc_close($h);

      return $stdout;
    }
  endif;

  // EOF

// action.php
  // файл команды для приложения
  
  require_once 'functions.php';
  $res = _doAsync(function () {
    echo 123;
  });

  // EOF

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
OnYourLips, 2017-03-21
@gzhegow

Use the ready-made library for creating processes, or at least look at its code: https://symfony.com/doc/current/components/process.html

$process = new Process('ls -lsa');
$process->start();

$process->wait(function ($type, $buffer) {
    if (Process::ERR === $type) {
        echo 'ERR > '.$buffer;
    } else {
        echo 'OUT > '.$buffer;
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question