My goal is to save the session of some process execution to json (smth like [{ type: 'stdout', data: 'What's your name?' }, { type: 'stdin', data: 'Alex.' }, { type: 'stdout', data: 'Hi, Alex!' }]
). I decided to do it with nodejs, but I've run into some problems. The stdout of spawned process works differently when being piped and when being inherited. So, for example I have this C code (simple guess number game) compiled to main
:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int random_num = 0;
int guessed_num = 0;
int counter = 0;
srand(time(NULL));
random_num = rand() % 10 + 1;
printf("Guess my number! ");
while(1) {
counter++;
scanf("%d", &guessed_num);
if (guessed_num == random_num) {
printf("You guessed correctly in %d tries! Congratulations!\n", counter);
break;
}
if (guessed_num < random_num)
printf("Your guess is too low. Guess again. ");
if (guessed_num > random_num)
printf("Your guess is too high. Guess again. ");
}
return 0;
}
And this JavaScript code:
var spawn = require('child_process').spawn;
var child = spawn('./main', { stdio: 'inherited' });
The result of execution of this JavaScript code will be:
Guess my number! 1
Your guess is too low. Guess again. 2
Your guess is too low. Guess again. 3
You guessed correctly in 3 tries! Congratulations!
However, when stdio
is inherited
, I can't attach to any of process streams and save the data to json. So I tried this:
var spawn = require('child_process').spawn;
var child = spawn('./main', { stdio: 'pipe' });
child.stdout.on('data', function(data) { process.stdout.write(data) });
process.stdin.on('data', function(data) { child.stdin.write(data) });
And get this as a result of execution:
1
2
3
Guess my number! Your guess is too low. Guess again. Your guess is too low. Guess again. You guessed correctly in 3 tries! Congratulations!
The stdout of child process is somehow hangs when the child process is waiting for input. Probably it has to do something with event-loop, but I'm not sure. Anyway, the behavior of inherited
and pipe
is very different and it seems wrong...
What can I do about it? Maybe there is some workaround?