Node.js process.send() 方法

Node.js process.send() 方法

process.send() 方法是 process 模块中的内置应用程序编程接口,被子进程用于与父进程进行通信。该方法在根进程中不起作用,因为它没有任何父进程。

语法:

process.send(message, [sendHandle])

参数: 此方法接受以下参数:

  • message: 要发送的消息。
  • sendHandle: Socket或Server对象。这是一个可选参数。

返回值: 布尔值。如果消息成功发送则返回true,否则返回false。

示例1: 首先,在Parent.js中,我们生成子进程。然后开始监听子进程。在Child.js中,我们在Child.js中获取消息。然后我们检查send方法是否可用,然后使用process.send()向父级发送消息。

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); 
  
// Start listening to the child process 
child.on('message', message => { 
  
    // Message from the child process 
    console.log('Message from child:', message); 
});

Child.js

console.log('In Child.js') 
  
// If the send method is available 
if(process.send) { 
  
    // Send Hello 
    process.send("Hello, this is child process."); 
}

运行 Parent.js 文件,使用以下命令:

node Parent.js

输出:

In Child.js
Message from child: Hello, this is child process.

示例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); 
  
// Start listening to the child process 
child.on('message', message => { 
  
    // Message from the child process 
    console.log('Message from child:', message); 
});

Child.js

console.log('In Child.js') 
  
// If the send method is available 
if(process.send) { 
  
    // Send Hello 
    process.send("Hello, this is child process."); 
  
    // Send multiple messages 
    setTimeout((function() { 
        return process.send("This was send after 1 second."); 
    }), 1000); 
  
    setTimeout((function() { 
        return process.send("This was send after 2 seconds."); 
    }), 2000); 
  
    setTimeout((function() { 
        return process.send("This was send after 3 seconds."); 
    }), 3000);  
}

使用以下命令运行 Parent.js 文件:

node Parent.js

输出:

In Child.js
Message from child: Hello, this is child process.
Message from child: This was sent after 1 second.
Message from child: This was sent after 2 seconds.
Message from child: This was sent after 3 seconds.

参考文献: https://nodejs.org/api/process.html#process_process_send_message_sendhandle_options_callback

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程