Search code examples
phpcexecpopenproc-open

Using proc_open() to run C executable in PHP


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!


Solution

  • what about?

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

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