I am trying to run a script on node.js, which sequentially sends numbers to executable a.out
, which squares it and writes the result to its stdout. When this happens, the next number will be sent. Here is the code:
var spawn = require('child_process').spawn; var p = spawn("./a.out",[],{"stdio":"pipe"}); p.stdout.setEncoding("utf8"); p.stdout.on("data",function(data){ var x = parseInt(data.trim()), y = Math.sqrt(x); console.log("received",x); if(++y===10) p.kill(); else { console.log("sending",y); p.stdin.write(y+"\n"); } }); var start = 2; console.log("sending",start); p.stdin.write(start+"\n"); setTimeout(function(){ p.stdin.end(); },1000);
where a.out
is the compiled version for the following C program:
#include<stdio.h> int main(){ int x; while(scanf("%d",&x)!=EOF) printf("%d\n",x*x); return 0; }
However, I get the following output:
sending 2 received 4 sending 3 events.js:72 throw er; // Unhandled 'error' event ^ Error: write after end
Changing the millisecond value in setTimeout
only delays the error. Apparently, the data that I am trying to send to a.out
is buffered and only sent when I end the channel. How to clean it manually?
source share