【新手求助】如何用node写一个守护进程 - CNode技术社区

【新手求助】如何用node写一个守护进程
发布于 13 年前 作者 ohsc 5212 次浏览 最后一次编辑是 9 年前

想用node一个守护进程的demo。目前看到的代码不是web服务就是net服务,都是依靠系统提供的listen接口来实现程序的持久执行的。

不借助http、net模块,如何写出一个event loop呢?

我能给出的方案是:

function Worker()
{
 this.MaxIterations = 1000000;
 this.Enabled = true; 
 this.condition = true;
 this.iteration = 0;
 this.Loop = function()
 {
 if (this.condition 
 && this.Enabled 
 && this.iteration++ < this.MaxIterations)
 {
 console.log(this.iteration);
 setTimeout(this.Loop.bind(this),0);
 }
 }; 
 this.Stop = function()
 {
 this.Enabled = false;
 };
}
var w = new Worker();
setTimeout(w.Loop.bind(w), 0);
setTimeout(w.Stop.bind(w), 3000);

大家有更好的吗?

8 回复

Node进程就是在eventloop下运行的啊

怎样让程序永远循环下去,并能处理event

@ohsc 能不能用 process.nextTick() 的?

@ohsc 想来想去还是和楼主一样... - -! 求助楼下...

这样行不行的...

delay = (t, f) -> setTimeout f, t
show = console.log
run = yes
worker = (n) ->
 if n < 10000000 and run
 show n
 show process.memoryUsage()
 process.nextTick -> worker (n + 1)
worker 1
delay 10000, -> run = no

奇怪我一直觉得 Node 用递归总是会栈溢出,' 这段代码又没报错, 这是怎么回事?

应该是process.nextTick的调用栈不太一样吧。 谁来证实一下。

function start(){ console.log(‘Mother process is running.’);

 var ls = require('child_process').spawn('node', ['app.js']);
 ls.stdout.on('data', function (data)
 {
 console.log(data.toString());
 });
 ls.stderr.on('data', function (data)
 {
 console.log(data.toString());
 });
 ls.on('exit', function (code)
 {
 console.log('child process exited with code ' + code);
 delete(ls);
 ls = null;
 setTimeout(start,3000);
 });

}

回到顶部

AltStyle によって変換されたページ (->オリジナル) /