Node.js - process.disconnect() 方法


当一个 Node.js 进程是通过 IPC 频道衍生的,process.disconnect() 方法将关闭该 IPC 频道到父进程,允许子进程正常退出或结束。一旦没有其他连接使该进程保持活动状态,该进程将退出。

语法

process.disconnect()

示例 1

创建两个名为 "parent.js""child.js" 的文件,并复制以下代码段。创建文件后,使用命令 "node parent.js" 运行 parent.js

parent.js

// process.channel Property Demo Example

// Importing the child_process modules
const fork = require('child_process').fork;

// Attaching the child process file
const child_file = 'child.js';

// Spawning/calling child process
const child = fork(child_file);

child.js

console.log('In Child Process')

// Checking if channel is available
if (process.connected) {

   // Check if its connected or not
   if (process.connected == true) {
      console.log("Child is connected.");
   }

   // Use process.disconnect() to disconnect with child
   process.disconnect();

   // Check if its connected or not
   if (process.connected == false) {
      console.log("Child is now disconnected.");
   }
}

输出

C:\home
ode>> node parent.js In Child Process Child is connected. Child is now disconnected.

示例 2

我们再看一个示例。

parent.js

// process.channel Property Demo Example

// Importing the child_process modules
const fork = require('child_process').fork;

// Attaching the child process file
const child_file = 'child.js';

// Spawning/calling child process
const child = fork(child_file);

child.js

console.log('In Child Process')

// Checking if channel is available
if (process.connected) {

   // Send multiple messages
   setTimeout((function () {
      if (process.connected == true) {
         console.log("Process Running for: 1 second.");
      }
   }), 1000);

   // Disconnect from channel after 2 seconds
   setTimeout((function () {
      if (process.connected == true) {
         console.log("Process Running for: 2 seconds.");
      }
   }), 2000);

   // Disconnect from channel after 2.5 seconds
   setTimeout((function () {
      process.disconnect();
   }), 2500);

   // Disconnect from channel after 3 seconds
   setTimeout((function () {
      if (process.connected == true) {
         console.log("Process Running for: 3 seconds.");
      }
   }), 3000);
}

输出

C:\home
ode>> node parent.js In Child Process Process Running for: 1 second. Process Running for: 2 seconds.

更新于: 17-Jan-2022

578 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告