Node.js – process.connected 屬性


process.connected 屬性在 IPC 通道已連線時返回 True,在呼叫了 process.disconnect() 方法後,將返回 False。僅當 node 程序透過 IPC 通道(即子程序和叢集)生成時,才會發生這種情況。

一旦 process.connected 屬性為 false,就無法透過 IPC 通道傳送任何訊息。

語法

process.connected

示例 1

Create two files "parent.js" and "child.js" as follows −

parent.js

// process.connected Property Demo Example

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

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

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

child.js

console.log('In Child')

// Check if IPC channel is connected
if (process.connected) {

   // Print response messages
   console.log("Child is connected");
} else {

   // Print messages
   console.log("Child is disconnected");
}

輸出

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

示例 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 = 'util.js';

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

util.js

console.log('In Child')

// Disconnect with the IPC channel
process.disconnect();

// Check if IPC channel is connected
if (process.connected) {

   // Print response messages
   console.log("Child is connected");
} else {

   // Print messages
   console.log("Child is disconnected");
}

輸出

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

更新於: 29-Oct-2021

73 次瀏覽

開啟你的 職業生涯

完成課程以獲取認證

開始
廣告