Why node.js running two process?

This is a simple example from the official doc:

$ node test-node.js 

var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  console.log(numCPUs);
  for (var i = 0; i < numCPUs-1; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  // Workers can share any TCP connection
  // In this case its a HTTP server
  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world\n");
  }).listen(8000);
}

This is what I see in htop: htop

There are 2 master processes and two forked processes.

Why? I thought that I should only have 2 processes!


UPDATE:

Here I'm running on VM CentOS: centos http://i.stack.imgur.com/GQiiN.png

Maybe I do not understand that?

Likely, node create system threads!

I'am enter console

[root@centos-1 ~]#  ps axf|grep node
 1435 pts/1    Sl+    0:00  |       \_ node /usr/local/bin/coffee test.js
 1445 pts/0    S+     0:00          \_ grep node
[root@centos-1 ~]#

but htop listing ~ 6 process 0_O (process and sub threads), but full memory ...

thanks for carma ;)

I created a small node server that runs an exec. The exec will spawn a new process (not a new thread; node does not use threads). Here's the process:

ps -ef | grep 32038
me  32038 15776  0 08:54 pts/7    00:00:00 node index.js
me  32116 32038  1 08:55 pts/7    00:00:00 find /home/me -name *.js

I looked in github, but in my cursory view, I did not see that http.createServer forks or spawns a new process. Having 2 processes makes sense because you are using the cluster API and you must have 2 CPU's or 1 CPU with 2 cores.


I ran your code above, and since I have 4 cores, I get 4 processes:

ps -ef | grep node
me   1822 15776  0 09:02 pts/7    00:00:00 node server.js
me   1827  1822  0 09:02 pts/7    00:00:00 /opt/node-v0.10.0-linux-x64/bin/node /home/me/workspace/node6proc2/server.js
me   1828  1822  0 09:02 pts/7    00:00:00 /opt/node-v0.10.0-linux-x64/bin/node /home/me/workspace/node6proc2/server.js
me   1830  1822  0 09:02 pts/7    00:00:00 /opt/node-v0.10.0-linux-x64/bin/node /home/me/workspace/node6proc2/server.js