2

I'm trying to make a very simple nodejs server that receives post requests and feeds them to a simple C program that makes all of its I/O through stdin and stdout. I'm trying to use the following script as a test:

var prc = require('child_process').spawn('./example');

// )none of these made it work)
prc.stdout.setEncoding('ascii');
//prc.stdout.setEncoding('utf8');

prc.stdout.on('data', function (data) {
    console.log("child said something: " + data);
});

prc.stderr.on('data', function (data) {
    console.log("stderr: " + data.toString());
});

prc.on('close', function (code) {
    console.log('process exit code ' + code);
});

setInterval(function() {
    console.log("gonna write");
    prc.stdin.write("prueba inicial\n");
    console.log("wrote");
}, 2000);

example.c contains:

int main() {
    int i;
    size_t size;
    char *line = NULL;

    for (i=0;;++i) {
        printf("\ngive me data: ");
        if (getline(&line, &size, stdin) != -1) {
            if (strcmp(line, "end\n") == 0) {
                break;
            }
            printf("result: %d, %d\n", i, i*2);
        }
    }

    return 0;
}

But the only thing I get on screen is

gonna write
wrote
gonna write
wrote
gonna write
wrote

I know example is running, but why am I not getting anything trough prc.stdout?

PD: may be it would be better to use sockets or something else to communicate with example, but this is just a test for a real project in which I'll be using another C program that I can't change.

Jk041
  • 934
  • 1
  • 15
  • 33
  • Have you checked the return value of `prc.stdin.write`? It may be buffering. You may also want to listen to the `exit` event on the `ChildProcess`. – Aaron Dufour Mar 08 '14 at 21:32
  • @AaronDufour It returns true, signifying the data was completely sent. – Jk041 Mar 09 '14 at 16:46
  • 1
    related: [Python C program subprocess hangs at “for line in iter”](http://stackoverflow.com/q/20503671/4279) – jfs Mar 09 '14 at 20:58

2 Answers2

2

Reason for needing fflush(stdout) is, because stdio detects you're not running in terminal, it will by default not flush on '\n', for improved data throughput.

So you can flush explicitly, or you change the buffering mode in your C code simply with

setvbuf(stdout, NULL, _IOLBF, 0);

Read this man page to learn more about this.

hyde
  • 60,639
  • 21
  • 115
  • 176
0

Apparently what fixed it was flushing stdout after every printf:

printf("result: %d, %d\n", i, i*2); 
fflush(stdout);

I tried that after seeing that the nodejs script got all the outputs when example.c was closed (by sending it end\n).

Jk041
  • 934
  • 1
  • 15
  • 33