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 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.