Generally, a single node is started to run in a single process. How can I run multiple processes like Nginx?
To implement multi-process, you need to pay attention to the two built-in node modules:
Child_process: Sub-Process Module
Net: Network Module
The Subprocess module of nodejs provides a send function, which is very useful and can pass the data of the main process to the subprocess.
That is to say, we can communicate with sub-processes through the send function.
Then we can implement a tcp server through the net module, and then pass handle to the sub-process. Then, the sub-process can monitor the same port to implement multiple processes.
Main process:
[Javascript]
Var child_process = require ('child _ Process ');
Var net = require ("net ");
Var tcp = net. createServer ();
Tcp. listen (listen, function (){
Console. log ('fork process start ');
Console. log ('Listen: '+ listen );
For (var I = 0; I <processLen; I ++ ){
Start_process (child_process, tcp, indexFile); // start the process
}
Console. log ('fork process end \ r \ n ');
Tcp. close ();
});
/*
* Start the process and monitor the process. If the process exits, the function is automatically called to restart it.
*/
Var start_process = function (child_process, tcp, indexFile ){
Var cp = child_process.fork (indexFile); // generate sub-process, indexFile process file address
Cp. send ('yes', tcp. _ handle); // send data to the child process
Console. log ('pid: '+ cp. pid );
Cp. on ('exit ', function (){
Start_process (child_process, tcp, indexFile );
})
}
Sub-process:
[Javascript]
// The sub-process receives the main process handle
Process. on ("message", function (m, handle) {// listen to the data transmitted by the main process through the process message
Http. createServer (_ this. on). listen (handle); // run the HTTP server
});