Nodejs Foundation-Multi-process

Source: Internet
Author: User

node. JS Multi-process

We all know that node. JS runs in single-threaded mode, but it uses event-driven to handle concurrency, which helps us to create multiple sub-processes on a multi-core CPU system to improve performance.

Each child process always has three stream objects: Child.stdin, Child.stdout, and Child.stderr. They may share the stdio stream of the parent process, or they can be independent stream objects that are channeled.

Node provides a child_process module to create a child process by:

    • EXEC -Child_process.exec uses the child process to execute commands, caches the output of the child process, and returns the output of the child process as a callback function parameter.

    • Spawn -Child_process.spawn creates a new thread with the specified command-line arguments.

    • Fork -Child_process.fork is a special form of spawn () that is used to run modules in child processes, such as fork ('./son.js ') equivalent to spawn (' node ', ['./son.js ']). Unlike the Spawn method, fork establishes a communication pipeline between the parent and child processes for communication between processes.

EXEC () method

Child_process.exec uses the child process to execute commands, caches the output of the child process, and returns the output of the child process as a callback function parameter .

The syntax is as follows:

Child_process.  EXEC(command[, options], callback)        
Parameters

The parameters are described as follows:

Command : string, commands to run, arguments separated by spaces

Options: objects, which can be:

    • CWD, string, the current working directory of the child process
    • Env, Object environment variable key value pair
    • Encoding, string, character encoding (default: ' UTF8 ')
    • Shell, string, shell that will execute the command (default: In Unix for /bin/sh , in Windows, the cmd.exe shell should be able to recognize the -c switch in Unix, or /s /c in Windows. command-line parsing should be compatible in Windows cmd.exe )
    • Timeout, number, time-out (default: 0)
    • Maxbuffer, number, the maximum buffer allowed in stdout or stderr (binary), if exceeded then the child process will be killed (default: 200*1024)
    • Killsignal, string, End signal (default: ' SIGTERM ')
    • UID, number, set ID of user process
    • GID, number, set ID of the process group

callback: callback function that contains three parameter error, stdout, and stderr.

The Exec () method returns the maximum buffer and waits for the end of the process to return the contents of the buffer at once.

Instance

Let's create two JS files Support.js and Master.js.

Support.js File Code:

Console.log ("process" + process.argv[2] + "execute. " );

Master.js File Code:

Const FS = require (' FS '); Const child_process= Require (' child_process '); for(vari=0; i<3; i++) {   varWorkerProcess = Child_process.exec (' node support.js ' +I,function(Error, stdout, stderr) {if(Error) {Console.log (error.stack); Console.log (' Error code: ' +Error.code); Console.log (' Signal Received: ' +error.signal); } console.log (' StdOut: ' +stdout); Console.log (' stderr: ' +stderr);      }); Workerprocess.on (' Exit ',function(code) {Console.log (' Child process has exited, exit code ' +code); });}
View Code

Execute the above code and the output is:

010002 execute. STDERR:
View Code

Spawn () method

Child_process.spawn creates a new thread with the specified command-line arguments in the following syntax format:

Child_process.  Spawn(command[, args] [, options])        
Parameters

The parameters are described as follows:

Command : commands that will be run

args: Array string parameter arrays

Options Object

    • Current working directory of the CWD String child process
    • ENV Object environment variable key value pair
    • Stdio array| Stdio configuration of a String child process
    • Detached Boolean This child process will become the leader of the process group
    • UID number sets the ID of the user process
    • GID number sets the ID of the process group

The spawn () method returns a stream (stdout & stderr), which is used when the process returns a large amount of data. Once the process starts executing, spawn () begins to receive the response.

Instance

Let's create two JS files Support.js and Master.js.

Support.js File Code:

Console.log ("process" + process.argv[2] + "execute. " );

Master.js File Code:

Const FS = require (' FS '); Const child_process= Require (' child_process ');  for(vari=0; i<3; i++) {   varWorkerProcess = Child_process.spawn (' node ', [' support.js '), I]); WorkerProcess.stdout.on (' Data ',function(data) {Console.log (' StdOut: ' +data);   }); WorkerProcess.stderr.on (' Data ',function(data) {Console.log (' stderr: ' +data);   }); Workerprocess.on (' Close ',function(code) {Console.log (' Child process has exited, exit code ' +code); });}
View Code

Execute the above code and the output is:

$ node Master.js stdout: Process 001020
View Code

Fork Method

Child_process.fork is a special form of the spawn () method that is used to create a process with the following syntax:

Child_process.  Fork(modulepath[, args] [, options])       
Parameters

The parameters are described as follows:

Modulepath: String, module to be run in child process

args: An array of array string arguments

Options: Object

    • Current working directory of the CWD String child process
    • ENV Object environment variable key value pair
    • Execpath String to create the child process executable file
    • EXECARGV an array of string parameters for the executable file of the array subprocess (default: PROCESS.EXECARGV)
    • Silent Boolean If it is true , the child process stdin , stdout and will be stderr associated to the parent process, otherwise they will inherit from the parent process. (Default is: false )
    • UID number sets the ID of the user process
    • GID number sets the ID of the process group

The returned object has a built-in communication channel in addition to all methods that have a childprocess instance.

H3> instances

Let's create two JS files Support.js and Master.js.

Support.js File Code:

Console.log ("process" + process.argv[2] + "execute. "= require (' fs '= require (' child_process 'for (var i=0; i<3; i++) {   var worker_process = child_process.fork ("Support.js", [i]);       Worker_process.on (function  (code) {      Console.log (' child process exited, exit code ' + code);   }); 
View Code

Execute the above code and the output is:

001020
View Code

Nodejs Foundation-Multi-process

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.