首页 > 解决方案 > node.js 第二个产生的子进程没有收到标准输入消息

问题描述

我的 node.js 脚本中有一个事件,需要多次调用它来产生一个子进程。当时不并行只有一个子进程。

    var child = spawn('node', [script, arg1],{cwd: "./", stdio:  ["pipe","pipe","pipe","ipc"]})

我需要向该子进程发送消息。在第一个生成的过程中,它可以正常工作:

      child.stdin.write("my_message")//also tried child.stdin.write("my_message\n")

生成的脚本上的侦听器如下所示:

process.stdin.on("data", async(data)=> {
    //dosomething
    process.exit();
 }

但是当第一个子进程完成并关闭并产生第二个子进程时,child.stdin.write("my_message")不会到达子进程。

我认为子进程退出时stdtin通道没有关闭有问题。所以我尝试了子进程以及和事件process.stdin.end();上的所有以下功能child.on("close")child.on("exit")

child.on("close", (data)=>{

console.log("Child process closed")
//child.stdin.end();
//child.stdout.end();
//child.stdin.destroy();
//child.kill("SIGINT");
//child = undefined;
//child.disconnect();
//child.ref(); })

我也尝试通过 ipc 发送消息。但是,当尝试向第二个生成的孩子发送消息时,这会引发“ERR_IPC_CHANNEL_CLOSED”。

节点--版本 v14.17.5

标签: javascriptnode.jsipcchild-processspawn

解决方案


将在外部模块中产生子进程和相关侦听器的功能外包实际上是有效的。不知道为什么。

//spawnChild.js
module.exports = function(arg1){

   var child = spawn('node', [script, arg1],{cwd: "./", stdio:  ["pipe","pipe","pipe","ipc"]})

   //plus the unmodified child.stderr, child.stdout... listeners in here
} 

在主脚本中调用新模块:

var childProcess = require("./spawnChild.js")(arg1)

推荐阅读