将带有 sh/bash 的 IPC 消息发送到父进程 (Node.js)

Send IPC message with sh/bash to parent process (Node.js)

我有一个 Node.js 进程,这个进程将一个 sh 子进程派生到 运行 一个 bash 脚本。像这样:

const cp = require('child_process');

const n = cp.spawn('sh',['foo.sh'], {
     stdio: ['ignore','ignore','ignore','ipc']
});

在我的 bash 脚本 (foo.sh) 中,如何将 IPC 消息发送回 Node.js 父进程?无法找到该怎么做。

再做一些研究,看来我会更接近 IPC 内部结构。可能有帮助的一件事是,如果我将父 PID 传递给 bash 脚本,那么也许我可以用它做点什么。

当您将'ipc'添加到您的stdio选项时,父进程和子进程将建立一个通信通道,并提供一个文件描述符供子进程使用。此描述符将在您的环境中定义为 $NODE_CHANNEL_FD。您可以将输出重定向到这个描述符,它将被发送到父进程进行解析和处理。

作为一个简单的例子,我将我的名字从 bash 脚本发送到要记录的父进程。

index.js

const cp = require('child_process');
const n = cp.spawn('sh', ['foo.sh'], {
    stdio: ['ignore', 'ignore', 'ignore', 'ipc']
});

n.on('message', (data) => {
    console.log('name: ' + data.name);
});

foo.sh

printf "{\"name\": \"Craig\"}\n" 1>&$NODE_CHANNEL_FD

基本上 bash 文件中发生的事情是:

  1. 我正在使用 printf 命令将 JSON 发送到 stdout,文件描述符 1。
  2. 然后将其重定向到 $NODE_CHANNEL_FD
  3. 的引用 (&)

Note that the JSON you send must be properly formatted and terminated with a \n character

如果你想从父进程发送数据到bash进程你可以添加

n.send({"message": "hello world"});

到您的 JavaScript,在 bash 文件中,您可以使用类似于

的内容
MESSAGE=read -u $NODE_CHANNEL_FD
echo " => message from parent process => $MESSAGE"

Note that you will have to change your stdio options so that you are not ignoring the standard output of the child process. You could set them to ['ignore', 1, 'ignore', 'ipc'] so that the child process' standard output goes straight to the parent's.