This article mainly shares with you node.js play process examples. node provides the child_process module. We then save the classic sample code as a worker.js file, as follows:
let http=require('http'); http.createServer(function (req,res) { res.writeHead(200,{'Content-Type':"text/plain"}); res.end('hello world') }).listen(Math.round((1+Math.random())*1000),'127.0.0.1');
Save the following code as master.js and start it through node master.js:
let fork=require('child_process').fork; let cpus=require('os').cpus();for(let i=0;i Copy after login
Check the number of processes through ps aux|grep worker.js under *nix systems.
This is the master-worker mode, also known as the master-slave mode.
The processes copied by fork are independent. This process has an independent and brand-new V8 instance. Forking a process is expensive.
The sub-process in the new version of node also has synchronous sub-process and asynchronous sub-process, here refers to the asynchronous sub-process
- spawn(): Start a child process
- exec(): Start a child process. The difference from spawn is that it has a callback function
- execFile(): Start a child process to execute the executable file
- fork(): Similar to spawn, the difference is that it only needs to specify the js file to create a node sub-process.
The difference between spawn and exec and execFile is that the timeout attribute can be specified when the latter two are created to set the timeout. time, the child process can be killed after the time is up.
The difference between exec and execFile is that exec is suitable for executing existing commands, and execFile is suitable for executing files.
let cp=require('child_process'); cp.spawn('node',['worker.js']);//没有回调函数cp.exec('node worker.js',function (err,stdout,stderr) {}); cp.execFile('worker.js',function (err,stdout,stderr) {}); cp.fork('./worker.js');
parent.js:
let cp=require('child_process');let n=cp.fork(__dirname+ './worker.js'); n.on('message',function (m) {}); n.send({hello:'world'});
Related recommendations:
Detailed explanation of PHP inter-process communication
The above is the detailed content of node.js fun process instance. For more information, please follow other related articles on the PHP Chinese website!