Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何手动将管道刷新到node.js中的子进程?_Node.js_Pipe_Flush_Child Process - Fatal编程技术网

如何手动将管道刷新到node.js中的子进程?

如何手动将管道刷新到node.js中的子进程?,node.js,pipe,flush,child-process,Node.js,Pipe,Flush,Child Process,我正在尝试在node.js上运行一个脚本,该脚本按顺序将数字发送到一个可执行文件a.out,该文件对其进行平方运算,并将结果写入其标准输出。发生这种情况时,将发送下一个号码。代码如下: var spawn = require('child_process').spawn; var p = spawn("./a.out",[],{"stdio":"pipe"}); p.stdout.setEncoding("utf8"); p.stdout.on("data",function(data){

我正在尝试在node.js上运行一个脚本,该脚本按顺序将数字发送到一个可执行文件
a.out
,该文件对其进行平方运算,并将结果写入其标准输出。发生这种情况时,将发送下一个号码。代码如下:

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);
其中
a.out
是以下C程序的编译版本:

#include<stdio.h>
int main(){
    int x;
    while(scanf("%d",&x)!=EOF)
        printf("%d\n",x*x);
    return 0;
}

setTimeout
中更改毫秒值只会延迟错误。显然,我试图发送到
a.out
的数据只有在我终止管道时才会被缓冲和发送。如何手动冲洗?

我整天都在做这个

问题是生成的进程的STDOUT需要刷新它的输出缓冲区,否则它会一直坐在那里直到填满为止,在这种情况下,代码将不会再次执行

p、 end()只用于结束进程,而进程本身就允许操作系统清除所有缓冲区

您不能从节点执行此操作,因为它不是输出缓冲区的所有者

这很烦人,但只要你控制了脚本,你就可以在那里修改它,也许允许它使用命令行选项来设置自动刷新


希望这能有所帮助。

您能详细说明我们是如何做到这一点的吗?一种典型的方法是将NUL字节作为刷新的信号。因此,每当您的C程序读取\0时,调用fflush。
sending 2
received 4
sending 3

events.js:72
    throw er; // Unhandled 'error' event
          ^
Error: write after end