I am making a Node.js app to compile and execute various c/c++ programs.
I am using child_process.exec(command[, options][, callback]) to run the commands "gcc test.c" to compile a c code written in test.c which takes user input and displays the output and "./a.out" to execute the file.
I can't find a way to execute it with user inputs, I only want to use child_process.exec() because I can handle infinite loops using options.timeout.
I have tried to compile and execute a c program without user inputs and it works fine.
I am using:
- Ubuntu 19.10
- Node.js v12.11.1.
- gcc (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008
test.c
#include <stdio.h>
int main() {
int n;
scanf("%d",&n);
printf("n = %d\n",n);
return 0;
}
node.js app
const cp = require("child_process");
const exec_options = {
cwd : "/home/hardik/Desktop" ,
timeout : 1000 ,
killSignal : "SIGTERM"
};
cp.exec("gcc test.c",exec_options,(error,stdout,stderr) => {
if(error) {
console.log(error);
}
else if(stderr) {
console.log(stderr);
}
else {
cp.exec("./a.out",exec_options,(error,stdout,stderr) => {
if(error) {
console.log(error);
}
else if(stderr) {
console.log(stderr);
}
else {
console.log("output : "+stdout);
}
})
}
});