0

I am trying to create a C program compiler + executer using PHP.

My PHP code is

<?php
    $cwd='/path/to/pwd';
    $descriptorspec = array(
    0 => array("pipe", "r"),
    1 => array("pipe", "w"),
    2 => array("file", "/path/to/log/file", "a") );

    $process = proc_open("./a.out", $descriptorspec, $pipes, $cwd);
    fwrite($pipes[0], 123);
    fclose($pipes[0]);
    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);
 

My C file is

#include <stdio.h>
int main() {
    int a;
    printf("Enter a number");
    scanf("%d", &a);
    printf("The value is: %d", a);
    return 0;
}

Now when I run this, I am getting the output

Enter a numberThe value is: 123

Is there anyway to do it like a terminal execution? So it should wait for the input after showing Enter a number. Then once I enter the number it will execute further and show the output.

It will be like a web site with a terminal.

Will it be possible with proc_open and PHP? Is it possible to achieve by using Web socket in some way?

Please help. Thanks in advance.

Arun
  • 3,640
  • 7
  • 44
  • 87
  • Interesting question! Effectively, you won't be able to stop the PHP so that the user can input the data like in a console. You'll very certainly have to deal with some JavaScript and web sockets might be a path towards the solution. I just don't know if you can have PHP processes that are running for a long time (without a timeout). Some console emulations such as [phpbash](https://github.com/Arrexel/phpbash) just send a command via Ajax, execute it and return it to the browser, but it's not what you are trying to do as your command is "blocking" for input/output. – Patrick Janser Feb 07 '22 at 12:35
  • @PatrickJanser, Thanks for spending time on this. By blocking I mean to wait for an input. So I can create kind of a terminal like UI experience. But I am not getting how to wait for input. It should go to the second input prompt when I enter the first input. – Arun Feb 07 '22 at 12:39
  • As Patrick is saying, HTTP in general, which is what PHP, the backing server and the web browser are all talking over, is request and response, both of which terminate as soon as possible. To “resume” or “continue” a conversation, you need to introduce state of some form, such as an ID cookie on the client side, and a cursor on the server side. And for you C code, you’d want to [detach](https://stackoverflow.com/a/19553986/231316) that process somehow, but what out for dangling processes. – Chris Haas Feb 07 '22 at 13:27
  • Perhaps you could dig with some [asynchronous PHP libraries and tools](https://github.com/elazar/asynchronous-php) and in [Symfony's process component](https://symfony.com/doc/current/components/process.html). But I don't think it will be easy :-/ – Patrick Janser Feb 07 '22 at 13:46

0 Answers0