Domanda

I am sorry (again) if you find this question noob. But I am really having a problem on proc_open.

I have a C file and I want to run it using proc_open() and read the input from a textfile. I was able to fetch and feed the input to the executable. The problem is that I just hardcoded the array of fetched strings.

PHP code fragments:

        $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]); 


        }

add2.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);
    }

streams on pipes[1] ( the printf's)

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

Question: Is there a "dynamic way" on how the "$input" elements will be laid out as input on

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

Or is there a more convenient way to get inputs from a file and feed it whenever there is scanf in the C executable that was ran by the proc_open().

(Btw, for those having trouble in proc_open(), especially for the starters like myself, I hope my codes help you somehow. This is my first time to make it run after few attempts so my codes are simple.)

And for the Pro's, please help meeeee. :( THANK YOU!

È stato utile?

Soluzione

what about?

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

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

Altri suggerimenti

Use 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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top