gpt4 book ai didi

node.js - 使用 node.js 运行 c 程序并获取响应

转载 作者:行者123 更新时间:2023-12-01 01:44:37 25 4
gpt4 key购买 nike

我试图在运行 C 程序的 node.js 中获得一个安全的“类似运行”的程序。我知道我必须使用子进程来实现我的目标......我选择 exec 因为它有一个回调参数:

执行程序

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

睾丸
#include <stdio.h>
void main(){
int i;
printf("Hello World\n");
}

这是我得到的输出:
stdout: Hello World

stderr:
exec error: Error: Command failed: ./teste

有人知道为什么会这样吗?
有更好的方法吗?
我怎样才能真正让超时工作?

谢谢

最佳答案

您的可执行文件在成功时应返回零值(无错误):

#include <stdio.h>
int main(){
int i;
printf("Hello World\n");

return 0;
}

如果没有,您可能会分配一个随机值,这表明存在某种错误。

关于node.js - 使用 node.js 运行 c 程序并获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52045069/

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