使用 proc_open() 在 PHP 中运行 C 可执行文件


Using proc_open() to run C executable in PHP

如果你

发现这个问题菜鸟,我很抱歉(再次(。但我在proc_open上确实遇到了问题。

我有一个 C 文件,我想使用 proc_open() 运行它并从文本文件中读取输入。我能够获取并将输入提供给可执行文件。问题是我只是硬编码了array of fetched strings.

PHP 代码片段:

        $descriptorspec = array(
            0 => array("pipe", "r"), 
            1 => array("pipe", "w"),  
            2 => array("file", "error.log", "a") 
        );
        $process = proc_open('C:/xampp/htdocs/ci_user/add2', $descriptorspec, $pipes);
        sleep(1);
        if (is_resource($process)) {
        //Read input.txt by line and store it in an array
        $input = file('C:/xampp/htdocs/ci_user/input.txt');
        //Feed the input (hardcoded)
        fwrite($pipes[0], "$input[0] $input[1]");
        fclose($pipes[0]);
        while ($s = fgets($pipes[1])) {
            print $s."</br>";
            flush();
        }
         fclose($pipes[1]); 

        }

添加2.c

    #include <stdio.h>
    int main(void) {
      int first, second;
      printf("Enter two integers > ");
      scanf("%d", &first);
        scanf("%d", &second);
      printf("The two numbers are: %d  %d'n", first, second);
      printf("Output: %d'n", first+second);
    }

管道上的流[1] ( printf的(

Enter two integers > The two numbers are: 8 2 
Output: 10 

问题:对于如何将">$input"元素布置为输入,是否有一种">动态方式">

            fwrite($pipes[0], "$input[0] $input[1]");

或者有没有更方便的方法可以从文件中获取输入并在proc_open()运行的 C 可执行文件中有scanf时馈送它。

(顺便说一句,对于那些在proc_open()遇到麻烦的人,特别是对于像我这样的初学者,我希望我的代码以某种方式对您有所帮助。这是我第一次在几次尝试后让它运行,所以我的代码很简单。

对于专业人士,请帮助我。 :(谢谢!

呢?

fwrite($pipes[0],implode(" ",$input));

http://php.net/manual/en/function.implode.php

使用stream_select:

do {
    $r = array($descriptorspec[1], $descriptorspec[2]);
    $w = array($descriptorspec[0]);
    $ret = stream_select($r, $w, $e, null);
    foreach($r as $s) {
      if($s === $descriptorspec[1]) {
        // read from stdout here
      } elseif($s === $descriptorspec[2]) {
        // read from stderr here
      }
    }
    foreach($w as $s) {
      if($s === $descriptorspec[0]) {
        // write to stdin here
      }
    }
  } while($ret);