运行 使用 node.js 的 c 程序并获得响应

Running c program with node.js and getting the response

我正在尝试在 node.js 中获取运行 C 程序的安全 "run-like" 程序。我知道我必须使用子进程来实现我的目标......我选择 exec 因为它有一个回调参数:

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 World\n");
}

这是我得到的输出:

stdout: Hello World

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

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

谢谢

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

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

  return 0;
}

如果不是,您可能分配了一个随机值,这表明存在某种错误。