Node.js process.disconnect() 方法

Node.js process.disconnect() 方法

process.disconnect() 属性是 process 模块中的内置应用程序编程接口,它被子进程用于与父进程断开连接。此方法不适用于根进程,因为它没有任何父进程。

语法:

process.disconnect()

参数: 不接受任何参数。

返回值: 没有返回值。

示例1: 在Parent.js中,我们生成子进程。在Child.js中,我们获得消息。在Child.js中,如果process.connected为真,就在控制台上打印一条消息并断开连接。

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 the send method is available 
if (process.connected) { 
  
    // Check if its connected or not 
    if (process.connected == true) { 
        console.log("Child.js is connected."); 
    } 
  
    // Use process.disconnect() to disconnect 
    process.disconnect(); 
  
    // Check if its connected or not 
    if (process.connected == false) { 
        console.log("Child.js has been disconnected."); 
    } 
}

使用以下命令运行 Parent.js

node Parent.js

输出:

In Child.js
Child.js is connected.
Child.js has been disconnected.

示例2: 在一段时间后断开连接。请注意,在断开连接函数运行后将不会打印任何消息。

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 the send method is available 
if (process.connected) { 
  
    // Send multiple messages 
    setTimeout((function () { 
        if (process.connected == true) { 
            console.log("This was sent after 1 second."); 
        } 
    }), 1000); 
  
    setTimeout((function () { 
        if (process.connected == true) { 
            console.log("This was sent after 2 seconds."); 
        } 
    }), 2000); 
  
    // Disconnect after 2.5 seconds 
    setTimeout((function () { 
        process.disconnect(); 
    }), 2500); 
  
    setTimeout((function () { 
        if (process.connected == true) { 
            console.log("This was sent after 3 seconds."); 
        } 
    }), 3000); 
}

使用以下命令运行 Parent.js

node Parent.js

输出:

In Child.js
Message from child: This was sent after 1 second.
Message from child: This was sent after 2 seconds.

参考: https://nodejs.org/api/process.html#process_process_disconnect

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程