How to manually clear a pipe to a child process in node.js?

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?

+4
source share
1 answer

I have been working on this all day.

The problem is that the STDOUT of your child process must clear the output buffer, otherwise it will sit there until it is full, in which case your code will not be executed again.

p.stdin.end () serves only to complete the process, which by its very nature allows the OS to clear all buffers.

You cannot do this from node, as this does not own the output buffer.

This is annoying, but as long as you control the script, you can change it there, perhaps let it use the command line parameter to set autorun?

Hope this helps.

+1
source

All Articles