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 次浏览

开启你的 职业生涯

完成课程以获取认证

开始
广告