gpt4 book ai didi

node.js - 如何使用 child_process.exec(command[, options][, callback]) 在 Node.js 应用程序中编译带有一些用户输入的 C 程序

转载 作者:太空宇宙 更新时间:2023-11-03 22:04:16 24 4
gpt4 key购买 nike

我正在制作一个 Node.js 应用程序来编译和执行各种 C/C++ 程序。

我正在使用 child_process.exec(command[, options][,callback]) 运行命令“gcc test.c”来编译 test.c 中编写的 c 代码,该代码接受用户输入并显示输出和“./a.out”来执行该文件。

我找不到使用用户输入执行它的方法,我只想使用 child_process.exec() 因为我可以使用 options.timeout 处理无限循环。

我尝试在没有用户输入的情况下编译和执行 C 程序,它工作得很好。

我正在使用:

  • Ubuntu 19.10
  • Node.js v12.11.1。
  • gcc(Ubuntu 9.2.1-9ubuntu2)9.2.1 20191008

测试.c

#include <stdio.h> 

int main() {
int n;
scanf("%d",&n);
printf("n = %d\n",n);
return 0;
}

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

最佳答案

您需要先将.exec()更改为.spawn()。这是因为 .exec() 缓冲输出,而 .spawn() 传输输出,因此它更适合交互式程序。另一件事是将 { stdio: 'inherit' } 添加到您的 exec_options 中。此外,如果它在 Windows 上运行,还需要添加另一个参数:{ shell: true }。总而言之,它应该看起来像这样:

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

关于node.js - 如何使用 child_process.exec(command[, options][, callback]) 在 Node.js 应用程序中编译带有一些用户输入的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58813578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com