Node.js process.connected 属性
process.connected 属性是进程模块的内置属性,子进程使用它来检查它是否连接到父进程。
句法:
process.connected
返回值:如果进程是从另一个进程派生的,那么如果两个进程已连接,则process.connected属性将返回 true,否则将返回 false。
示例 1:如果进程已连接,则 process.connected 将返回 true。
Parent.js
// Require fork method from child_process
// to spawn child process
const fork = require('child_process').fork;
// Child process file
const child_file = 'Child.js';
// Spawn child process
const child = fork(child_file);
Child.js
console.log('In Child.js')
// If it is connected
if (process.connected) {
// Print messages
console.log("Child.js is connected");
} else {
// Print messages
console.log("Child.js is disconnected");
}
Parent.js
// Require fork method from child_process
// to spawn child process
const fork = require('child_process').fork;
// Child process file
const child_file = 'Child.js';
// Spawn child process
const child = fork(child_file);
Child.js
console.log('In Child.js')
// Disconnect the process
process.disconnect();
// If it is connected
if (process.connected) {
// Print messages
console.log("Child.js is connected");
} else {
// Print messages
console.log("Child.js is disconnected");
}
Child.js
console.log('In Child.js')
// If it is connected
if (process.connected) {
// Print messages
console.log("Child.js is connected");
} else {
// Print messages
console.log("Child.js is disconnected");
}
使用以下命令运行Parent.js文件:
node Parent.js
输出:
In Child.js
Child.js is connected
示例 2:如果进程断开连接,则 process.connected 将返回 false。
父.js
// Require fork method from child_process
// to spawn child process
const fork = require('child_process').fork;
// Child process file
const child_file = 'Child.js';
// Spawn child process
const child = fork(child_file);
Child.js
console.log('In Child.js')
// Disconnect the process
process.disconnect();
// If it is connected
if (process.connected) {
// Print messages
console.log("Child.js is connected");
} else {
// Print messages
console.log("Child.js is disconnected");
}
使用以下命令运行Parent.js文件:
node Parent.js
输出:
In Child.js
Child.js is disconnected
参考: https://nodejs.org/api/process.html#process_process_connected