Jk041
Jk041

Reputation: 982

Can't get anything from the stdout of a child process

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.

Upvotes: 2

Views: 496

Answers (2)

hyde
hyde

Reputation: 62787

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.

Upvotes: 2

Jk041
Jk041

Reputation: 982

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).

Upvotes: 0

Related Questions