简体   繁体   中英

How to compile a c program with some user inputs in Node.js app using child_process.exec(command[, options][, callback])

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM