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

1
  • Do you know the integers beforehand? Commented May 19, 2012 at 16:07

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Wow....it works as expected. Thanks a lot chris, but what about in case a.out raise an error, how I will capture that?
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.
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.
you should mark this answer as accepted and post a new question with your updated code which demonstrates the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.