[英]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.我正在制作一个 Node.js 应用程序来编译和执行各种 c/c++ 程序。
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 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" 来执行文件。
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.我找不到使用用户输入执行它的方法,我只想使用 child_process.exec() 因为我可以使用 options.timeout 处理无限循环。
I have tried to compile and execute a c program without user inputs and it works fine.我试图在没有用户输入的情况下编译和执行 c 程序,它工作正常。
I am using:我在用:
test.c测试.c
#include <stdio.h>
int main() {
int n;
scanf("%d",&n);
printf("n = %d\n",n);
return 0;
}
node.js app node.js 应用程序
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.您需要
.exec()
更改为.spawn()
。 It's because .exec()
buffers the output while the .spawn()
streams it so it's more suitable for the interactive program.这是因为
.exec()
缓冲 output 而.spawn()
流式传输它,因此它更适合交互式程序。 Another thing is to add { stdio: 'inherit' }
to your exec_options
.另一件事是将
{ stdio: 'inherit' }
添加到您的exec_options
中。 Additionally, if it's running on Windows, there's another parameter to add: { shell: true }
.此外,如果它在 Windows 上运行,还需要添加另一个参数:
{ 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.