Writing Daemons in Javascript with node.JS
At some point, while developing a web-framework with node.js, I thought it would be nice if I could create Daemons in Javascript(no wrappers!). So I've created this very simple module for node.js. It's called daemon.node. Basically, it makes system calls that are required to create a working daemon.
Before I jump in explaining how it works and how to use it, I want to show you how simple it is to create a daemon with this module.
That's it. Just require() the daemon module and call daemon.start(). Of course, it's an oversimplified example, but it is going to produce a working daemon. I'll try to show you more useful examples below.
What is a daemon and how to create it..
Basically, a daemon is a process that runs in the background. I'm not going to talk about Windows daemons(they're called services), but rather focus on traditional *nix daemons.
Without going into the details, in order to become a daemon, a program goes through these steps:
- fork() from a parent process.
- Terminate parent process.
- Create new session with setsid().
- umask() sets file mode creation mask.
- chdir() sets working directory.
- Close stdin, stdout, stderr. The preferred way is to use logging(custom or syslog).
Comments (12)
The same script runs fine if I comment out the daemon module lines, and I can connect to my servers.
Is there any obvious reason why I connect to, but not receive data from, any node server running in the daemon forked process?
If I remove the call to closeIO(), it works as advertised.
Not sure if this is a problem with my system, node,v8, or daemon.node.
Example: fs.readFileSync(lockFile).toString() => 17284
ps -ef | grep node =>
admin 1728 1 0 18:26 ? 00:00:01 node app/app.js start
So then when invoking stop, it obviously does not find the process:
/home/admin/www/testing/app/app.js:15
process.kill(parseInt(fs.readFileSync(pidFile)));
^
Error: No such process
at Object.<anonymous> (/home/admin/www/testing/app/app.js:15:11)
at Module._compile (module:384:23)
at Module._loadScriptSync (module:393:8)
at Module.loadSync (module:296:10)
at Object.runMain (module:447:22)
at node.js:208:10
Using node 0.1.98 on Ubuntu. It doesn't seem to happen on Snow Leopard. Any ideas?
The pid in the tempfile is wrong in your case because the pidfile is not deleted on each run, the file is not opened with O_TRUNC set, and pid values can be different lengths over time. So, when pid values roll over from longer to shorter, if your old pidfile had a long value in it then an incorrect value will be written.
The solution is to patch LockD() in daemon.cc to include O_TRUNC option on open().
(libev) kevent: Bad file descriptor
Since the error is so generic, I'm not sure what would be causing it. I followed the example code closely as well. Any ideas? Thanks!
Thanks! Your module was very useful for me!
See my guide on using this with Ubuntu... it really would work for any unix based distribution.
Any clue on how to address this?