javascript - 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
解决方案
将在外部模块中产生子进程和相关侦听器的功能外包实际上是有效的。不知道为什么。
//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)
推荐阅读
- php - 当表单在单独的树枝中呈现时如何访问表单输入?
- phaser-framework - 将图像从 JS 加载到 Phaser 游戏
- javascript - ngRx 操作未正确分派
- c++ - 我的程序没有从文件中读取并输入数据
- graph-databases - 如何对 CMS 的图形数据库中节点的访问权限进行最佳建模
- javascript - 制作具有firestore和云功能的跟随系统
- python - 如何修复此函数语法?
- python - 如何使用贝叶斯优化(在 Python 中)在超参数空间上调整超参数?
- flutter - 如何在数字增加时对其进行动画处理
- javascript - 需要两次按下的反应按钮