Running c program with node.js and getting the response

Viewed 642

I am trying to get a secure "run-like" program in node.js that runs C programs. I understand that I must use a child process to achieve my goal... And I choose exec because it has a callback arguments:

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

this is the output I am getting:

stdout: Hello World

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

Someone knows why this is happening? There is a better way of doing that? How can I really get timout working?

Thanks

1 Answers

Your executable should return a zero value (no error) on success:

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

  return 0;
}

If it doesn't you may have a random value assigned and that indicates some kind of error.

Related