2

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);
            }
        })
    }
});

1 Answer 1

1

You need to change .exec() to .spawn() first. It's because .exec() buffers the output while the .spawn() streams it so it's more suitable for the interactive program. Another thing is to add { stdio: 'inherit' } to your exec_options. Additionally, if it's running on Windows, there's another parameter to add: { shell: true }. To sum up, it should look something like this:

const isWindows = process.platform === 'win32';
const exec_options = {
    cwd : "/home/hardik/Desktop" ,
    timeout : 1000 ,
    killSignal : "SIGTERM",
    stdio: 'inherit',
    ...(isWindows && { shell: true })
};

const run = cp.spawn("./a.out", [], exec_options);

run.on('error', console.error);
Sign up to request clarification or add additional context in comments.

Comments

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.