2

Need a help to implement the following. I have a C program file as follows:

#include <stdio.h>

main()
{
  int x;
  int args;

  printf("Enter an integer: ");
  if (( args = scanf("%d", &x)) == 0) {
      printf("Error: not an integer\n");
  } else {
      printf("Read in %d\n", x);
  }
  if (( args = scanf("%d", &x)) == 0) {
      printf("Error: not an integer\n");
  } else {
      printf("Read in %d\n", x);
  }
}

I generated a.out and now I want to call this a.out using exec("a.out", $output). But my problem is that I'm getting how to pass the value of integer when it asks for. I tried using proc_open() but I could not understand its usage. I will appreciate your help if you can give me piece of PHP code which can handle this to pass these two values and finally print the received result.

Best Regards

Christian
  • 27,509
  • 17
  • 111
  • 155
user1405309
  • 397
  • 1
  • 4
  • 11

1 Answers1

3

my guess would be

$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w")
);




$process = proc_open('/full/path/to/a.out', $descriptorspec, $pipes);

if (is_resource($process)) {
    list ($out, $in) = $pipes;

    fwrite($out, "5\n");
    fwrite($out, "7\n");

    echo stream_get_contents($in);
}
goat
  • 31,486
  • 7
  • 73
  • 96
  • Wow....it works as expected. Thanks a lot chris, but what about in case a.out raise an error, how I will capture that? – user1405309 May 19 '12 at 16:16
  • try adding another "w" mode pipe to the descriptor array, then you can read the programs stderr. you may want to investigate php's stream_set_blocking() or stream_select() functions so you can check the err pipe without blocking. – goat May 19 '12 at 16:30
  • Hi Chris, I got a situation where if I do not pass 7 then as well my program is printing value 5 for both the prinf() statements. I could not understand why it is picking same value for two scanf() statements. – user1405309 May 20 '12 at 19:50
  • 1
    you should mark this answer as accepted and post a new question with your updated code which demonstrates the issue. – goat May 20 '12 at 20:00