Search code examples
c++command-lineexecution

Online Compiler - Intercept a program when it waits for input and feed it input automatically


Context

I have written a toy compiler for a college project. Now I am making a website for the compiler, and I want to allow visitors to be able to write code in my language on it's website itself, then run it in a sort of virtual terminal in the browser. Sort of like the Go language and Haskell language websites.

A Virtual Private Server(VPS) or some cloud function can compile the user-written code using my compiler. Then the server can run it too, but it would have to monitor the program so that:

  1. If the program writes anything to STDOUT, the server will send the data to front-end which will display it on the virtual terminal. One way might be to redirect the output with >.

  2. Every time the program asks for an input, server will notify the front-end. Then front-end sends back the text typed in the virtual terminal, which the server injects into STDIN.

I think I'll use NodeJS for the server.

Question

How do I know when an executable waits for input and how do I feed it when it does? Is there some pre-built mechanism or will I have to write a monitoring program?.

Here are a few ways I have thought about:

  1. Have a Valgrind style virtual machine that runs the generated executable. I am definitely not going to go this far.

  2. Modify my compiler so that for every "input" command in the language, it generates assembly code to actually write to a file that it needs input (which is being polled by the server) and watch another file for changes (where the server will write the incoming input).

I'm hoping there is a simpler way. Also, if what I'm trying to do has a more descriptive name and documentation, please let me know.


Solution

  • How do I know when an executable waits for input

    You don't (need to). Just read the virtual terminal whenever the user types in it, and stuff the standard input with what you read. When and if the executable needs an input, it will be there.

    This is how any real or virtual terminal on every Unix-like system works. This is what you would do if you were to write a normal terminal emulator. There's no need to do it any differently just because you are connected to your terminal emulator via HTTP.