我正在尝试在 node.js 中获取一个运行 C 程序的安全"类似运行"的程序。我知道我必须使用子进程来实现我的目标......我选择 exec 是因为它有一个回调参数:
执行.js
const { exec } = require('child_process');
var options = {
timeout: 100,
stdio: 'inherit',
shell: true,
}
exec('gcc teste.c -o teste', (error, stdout, stderr) => {
exec('./teste', options, (error,stdout,stderr)=>{
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error) {
console.error(`exec error: ${error}`);
return;
}
});
});
Teste.c
#include <stdio.h>
void main(){
int i;
printf("Hello Worldn");
}
这是我得到的输出:
stdout: Hello World
stderr:
exec error: Error: Command failed: ./teste
有人知道为什么会这样吗? 有更好的方法吗? 我怎样才能真正让超时工作?
谢谢
您的可执行文件在成功时应返回零值(无错误(:
#include <stdio.h>
int main(){
int i;
printf("Hello Worldn");
return 0;
}
如果没有,您可能分配了一个随机值,这表明存在某种错误。