child_process.spawn 上的 node.js EPIPE 异常

标签 node.js spawn epipe

我正在使用 node.js v0.6.10 尽管我在 0.6.7 上遇到了同样的问题。基本上我使用 spawn 运行一个子进程,它启动另一个 node.js 进程,并通过 stdoutstdin 进行通信这是两个脚本:

父级(cli.js):

var spawn = require("child_process").spawn;

var doSpawn = function(callback){
  var child = spawn('child.js');

  child.on('exit', function(code){
    console.log("Child exited with code " + code);
  });

  child.stdin.write("ping");
  child.stdin.end();
};


doSpawn();

setTimeout(function(){}, 10000);

child.js

var run = function(){
  process.stdout.on('drain', function(){
    process.exit(0);
  });

  process.stdout.write(stdout);
};

var stdin = process.stdin;

stdin.resume();
stdin.setEncoding("utf8");

var stdout = '';

stdin.on('data', function(data){
  stdout += data;
});

stdin.on('end', run);

然后当我运行 node cli.js 时:

$ node cli.js 

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: write EPIPE
    at errnoException (net.js:642:11)
    at Object.afterWrite [as oncomplete] (net.js:480:18)

最佳答案

建议运行另一个 Node 进程*child_process.fork()* http://nodejs.org/docs/latest/api/child_processes.html#child_process.fork

修改后的代码:

var cp = require("child_process");

var doSpawn = function(callback){
  var child = cp.fork('child.js');

  child.on('exit', function(code){
    console.log("Child exited with code " + code);
  });

  child.stdin.write("ping");
  child.stdin.end();
};


doSpawn();

setTimeout(function(){}, 10000);

关于child_process.spawn 上的 node.js EPIPE 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9245126/

相关文章:

node.js - 错误: EBUSY: resource busy or locked, rmdir

node.js - Nodejs、PM2 和 nginx 部署安全性?

io - 从模板执行中过滤掉损坏的管道错误

javascript - 子进程何时终止

node.js - 使用 nohup/supervise 命令的日志重定向问题

c - EPIPE错误没有出现?

node.js - 如何在没有模式的情况下创建 Mongoose Provider。嵌套

node.js - Websocket (node.js) 连接限制,客户端在达到 400-450 个连接后断开连接

perl - 为什么 Perl 的 "system (' 某些命令')"与 c :\> some command? 的行为不同

Node.js - 生成的进程正在生成错误 "execvp(): No such file or directory"