【转】Writing Daemons in Javascript with node.JS

April 1, 2010

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:

  1. fork() from a parent process.
  2. Terminate parent process.
  3. Create new session with setsid().
This is the minimum requirement for a daemon. If any of these steps fail, the process won't become a daemon.
Now, it is preferred for a daemon to take these additional steps:
  1. umask() sets file mode creation mask.
  2. chdir() sets working directory.
  3. Close stdin, stdout, stderr. The preferred way is to use logging(custom or syslog).
Basically, the daemon.start() function forks, kills parent, creates new session, umasks, chdirs.
In order to close stdin, stdout and stderr, you will have to calldaemon.closeIO() function.
By default, umask() is called with the first argument set to 0, and chdir() changes working directory to the root "/". After daemon has been created you can use node's built in functions to alter these settings to your needs: process.umask andprocess.chdir.
Here's an example:

 

 

There's one problem though. How do you know that only one instance of your daemon will be started? The traditional way for this is to use file locks. Daemon creates a file lock. Common convention is to use "/tmp/[daemon_name].lock" or "/var/run/[daemon_name].pid". Then daemon usually writes its own PID to that file, as it can be useful. When daemon terminates it will automatically unlock the file and a new daemon can be started. To create a lock file, you use a module functiondaemon.lock([filename]). if [filename] doesn't exist, the function creates it automatically.

 

Example: HTTP-Server daemon.
Here is a complete(well, almost complete) implementation of our hellohttpd.

 

It's pretty simple and straightforward, so I won't go into explanations here. Now, this example still doesn't implement signal handling. Basically, you would want to handle these two signals SIGHUP and SIGTERM. Many servers use SIGHUP to restart, so it's a good idea to do some serialization, etc. work there. To catch these signals, you should use process.addListener("SIGTERM", function() { ... } );
Hope, you'll find it useful. :)

Comments (12)

Apr 02, 2010
HB said...
Thanks for this simple module and great explanation of how it works. I'll be trying this out this weekend for sure!
Apr 03, 2010
【转】Writing <wbr>Daemons <wbr>in <wbr>Javascript <wbr>with <wbr>node.JS
Arthur said...
@HB I hope it works you. Let me know if you have any trouble.
Thanks.
Apr 06, 2010
nefD said...
Thanks muchly for this! Solves roughly three deployment issues for me.. Here's hoping it will continue to be updated or stay compatible with the rapidly released node updates. :)
Apr 08, 2010
【转】Writing <wbr>Daemons <wbr>in <wbr>Javascript <wbr>with <wbr>node.JS
Arthur said...
@nefD It should be compatible with future releases as it depends rather on how V8 works, but I'll try to keep it up-to-date. I'm very glad it was useful for you.
May 31, 2010
satori said...
Hi, when I run your example it runs without errors, but any type of server that is started in the forked process never returns any data to my client.

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?

May 31, 2010
satori said...
I worked this out. Calling daemon.closeIO() stops my node server in the forked process from receiving any new requests. Connections are accepted, but no new requests are fired.

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.

Jun 15, 2010
Francisco said...
Nice module! But something strange occurs sometimes... it writes the pid in the lock file, but the process id is actually one digit less.

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?

Jun 30, 2010
Wayne said...
@Francisco

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().

Sep 06, 2010
Ryan said...
Exactly what I was looking for, but unfortunately I can't seem to get it to work. When trying to daemonize, I get the error:

(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!

Oct 06, 2010
Kip said...
http://utahjs.com/2010/09/24/running-a-nodejs-server-as-a-daemon-on-ubuntu/

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.

Oct 14, 2010
【转】Writing <wbr>Daemons <wbr>in <wbr>Javascript <wbr>with <wbr>node.JS
tajur said...
It seems daemon-node is not properly working on Mac OS X. I also get this error: "(libev) kevent: Bad file descriptor" when trying to start a daemon. Seems to be related to kqueue, but the error is pretty generic and won't help much at debugging.

Any clue on how to address this?

Nov 04, 2010
dswift said...
Instead of closing the streams in this module, you should probably just redirect them, so that you can still process connections.

freopen( "/dev/null", "r", stdin);
freopen( "/dev/null", "w", stdout);
freopen( "/dev/null", "w", stderr);

Claude Code vs Codex Claude Code 提供了一个生产就绪(production-ready)的实现,包含良好的错误处理、优雅的关闭逻辑、详细注释和文档,以及内置测试。Claude Code 输出了一个可运行的 Next.js + TypeScript 前端,但错过了一些设计里的黄色主题元素;Codex 则生成自己的版本,没有导出设计中的图片,也没严格遵照设计主题。Codex 完成同样功能,但更简洁直接,文档和注释少一些但功能达标。任务都用同样的提示,使用 TypeScript 实现,并在一天内完成。 阅读详情

相关推荐

数理金融学笔记 Chap2 二叉树模型Binomial

2 二叉树模型与期权定价 Binomial Model and Option Pricing 文章目录2 二叉树模型与期权定价 Binomial Model and Option Pricing单期二叉树模型 One-step Binomial Model风险与无风险资产单期二叉树模型与无套利条件无套利定价 No Arbitrage Pricing风险中性定价 Risk Neutral PricingDelta套期保值 Delta Hedging两期二叉树模型 Two-Step Binomial Model

weixin_66831131的博客 2397

环信 GitHub 仓库索引——全部SDK、UIKit 与 CallKit、Demo 与集成示例

本文档汇总环信官方及社区GitHub仓库,涵盖多端IM SDK、UIKit、CallKit组件及完整Demo,支持iOS、Android、Flutter、React Native、HarmonyOS等平台,提供快速集成与开发参考。

huan132456765的博客 213

优化QT QML中RTSP流播放延迟:海康摄像头实时监控实践

本文详细探讨了在QT QML中优化海康摄像头RTSP流播放延迟的实践方法。通过调整MediaPlayer缓冲策略、硬件加速、解码器优选等五大技巧,显著降低实时监控场景下的延迟问题。文章还提供了海康摄像头RTSP连接实战代码和避坑指南,帮助开发者快速实现高效流媒体播放。

weixin_28363123的博客 560

JS 打印空白页:网页打印控件 iframe 时序排查与修复

从整页空白复现出发,定位 iframe onload 与 document.write 的时序竞争。本文结合具体场景讲清做法、常见问题与可复用的实现思路。

一天拉了7遍的博客 137

舵机操作手册

微型伺服马达原理与控制(中鸣) 1、微型伺服马达内部结构一个微型伺服马达内部包括了一个小型直流马达;一组变速齿轮组;一个反馈可调电位器;及一块电子控制板。其中,高速转动的直流马达提供了原始动力,带动变速(减速)齿轮组,使之产生高扭力的输出,齿轮组的变速比愈大,伺服马达的输出扭力也愈大,也就是说越能承受更大的重量,但转动的速度也愈低。 2、微行伺服马达的工作原理一个微型伺服马达是一个典型闭环反馈系统,其原理可由下图表示: 减速齿轮组由马达驱动,其终端(输出端)带动一个线性的比例电位器作位置检测,该电位器把

HEIMENGER的博客 3145

SAP特殊采购类80实战:跨工厂生产配置避坑指南(附完整测试流程)

本文深入解析SAP特殊采购类80在跨工厂生产场景下的实战应用与配置要点。文章从核心业务逻辑出发,详细拆解了后台配置、主数据与BOM的“双工厂”思维模式,并提供了从创建需求到成品收货的完整测试流程。重点揭示了多层BOM下的需求传递陷阱及常见报错解决方案,旨在帮助SAP顾问及用户规避实施风险,实现资源的灵活调度与流程自动化。

wind6的博客 1147

基于Docker Compose 部署RuoYi-Vue 前后端分离后台管理系统

RuoYi-Vue是前后端分离的后台管理系统若依是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。是一个 Java EE 企业级快速开发平台,基于经典技术组合(Spring Boot、Spring Security、MyBatis、Jwt、Vue),内置模块如:部门管理、角色用户、菜单及按钮授权、数据权限、系统参数、日志管理、通知公告、代码生成等。在线定时任务配置,支持集群,支持多数据源,支持分布式事务等。

一直在努力学习的菜鸟 216

Alphafold2/multimer Conda环境配置与GPU加速优化指南

本文详细介绍了如何在本地服务器或工作站上,通过Conda环境配置并优化GPU加速来部署Alphafold2及其多聚体版本Alphafold2-multimer。内容涵盖从硬件准备、依赖安装、数据库部署到实战预测与常见报错处理的全流程,重点解决了本地安装过程中的依赖冲突与GPU调用失败等关键问题,帮助研究人员高效运行这一蛋白质结构预测工具。

neovim7hacker的博客 475

靓车汽车销售网站设计与实现:SpringBoot 汽车销售 203 个接口,附论文与运行截图

# 靓车汽车销售网站设计与实现:SpringBoot 汽车销售 203 个接口,附论文与运行截图 ## 目录 - [一、你是不是也这样](#一你是不是也这样) - [二、这套是什么](#二这套是什么) - [三、对你具体有什么用](#三对你具体有什么用) - [四、怎么跑起来](#四怎么跑起来) - [五、里面有什么](#五里面有什么) --- ## 一、你是不是也这样 选题报到「销售网

面朝大海 352

ABAP RANGES及比较符号

RANGES *选项介绍: *1.SIGN 值为 I 和 E 。 I是包含, E是排除, 一般使用I。 2.OPTION 如果HIGH 为空 ,为单值选择 。有 EQ、NE、GT、LE、LT等逻辑操作 对于的 CP包含 NP是排除 如果HIGH 不为空 为区间选择 有BT,NB可选 *3.LOW 低值 *4.HIGH 高值 lt:less than 小于 le:less than or equal to 小于等于 eq:equal to 等于 ne:

Pegasus666的博客 5401

EMD (经验模态分解) 在 C++ 中的实现指南

EMD 是由 Norden E. Huang 等人在1998年提出的一种适用于非线性和非平稳信号的分析方法。对称性:IMF 的上下包络对称。零交叉点:IMF 的零交叉点数量与极值点数量相同或相差一个。本文详细介绍了如何在C++中实现EMD,包括理论背景、算法步骤、代码实现和优化等内容。通过丰富的代码示例和详细的解释,希望能够帮助读者掌握EMD的基本原理,并能够在实际项目中灵活应用。未来,随着信号处理技术的不断发展,EMD及其变种(如EEMD、CEEMDAN等)将继续在各个领域发挥重要作用。

qq_38334677的博客 1756

副队长 Vue3 教程(19)--组件 props 父传子

本文讲解Vue组件通信中的props机制,实现父组件向子组件传递数据。通过defineProps对象写法进行类型校验、必填判断与默认值设置,推荐用于正式项目。重点强调单向数据流原则:子组件不可直接修改props,避免数据污染。结合待办清单案例,演示如何循环渲染多条待办项,并指出常见错误如直接修改props、默认值未用函数返回等。最后提示后续学习defineEmits实现子传父。

编程副队长 314

基于RAG(Retrieval Augmented Generation)架构的简单问答系统的Python实现示例

以下是一个基于RAG(Retrieval Augmented Generation)架构的简单问答系统的Python实现示例。这个系统使用langchain库进行文档处理、检索,以及与大语言模型交互。

max500600的博客 745

网页打印控件选型:LODOP 与 vue-print-designer 成本对比

不比功能清单,比授权方式、部署改动量和信创适配成本。本文结合具体场景讲清做法、常见问题与可复用的实现思路。

一天拉了7遍的博客 158

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Vue 自定义事件

Vue中自定义事件通过“发布-订阅”模式实现子组件向父组件通信。父组件用@event监听,子组件用defineEmits触发事件并传递参数。支持动态事件名、.once修饰符及编程式绑定。推荐在Vue3中使用<script setup>与defineEmits,简洁高效。示例中子组件点击触发greet事件,父组件接收消息并更新状态,实现双向数据流动。

cccloveforever的博客 422

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

javascript 基础 es6:4、Symbol,Symbol创建对象属性,Symbol内置属性,迭代器,迭代器自定义遍历对象

本文介绍了ES6中Symbol的创建与特性,包括Symbol()和Symbol.for()的区别,Symbol作为唯一属性名解决命名冲突;通过[Symbol()]方式安全添加对象属性;利用内置Symbol属性(如Symbol.isConcatSpreadable)自定义行为;最后讲解迭代器机制,通过Symbol.iterator实现自定义遍历逻辑,支持for...of循环。

狮子座的男孩 187

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

用 Vue 3 和 Spring Boot 构建煤矿三屏驾驶舱

该调度室驾驶舱系统以Vue3与Vite构建,通过单一入口集成人员安全、生产监测与用电监测三类视图,实现数据统一展示。各视图共用导航与状态栏,支持通过URL切换并保留全屏与历史记录。人员安全页基于HTTP首屏与SSE推送实时更新井下人数、告警与定位;生产页区分班次与时段完成率,动态展示产量趋势;用电页联动拓扑图与负荷曲线,精准呈现回路负载与电量。采用版本号防覆盖机制保障数据一致性,布局使用CSS Grid优化空间分配,确保关键信息清晰可读。系统已通过多分辨率验证,后续将对接真实数据源,实现全场景应用。

王元帅的博客 277

副队长 Vue3 教程(16)--Vue3项目样式管理方案

本文详解Vue组件中的样式作用域问题,重点介绍scoped实现局部样式隔离的原理与使用,避免样式污染。同时讲解全局样式、外部CSS引入及Sass预处理器的配置与应用。强调Sass为可选增强工具,原生CSS已足够开发,建议优先使用scoped提升代码可维护性。

编程副队长 395

电商订单系统中CSS响应式布局与动画的反模式集锦

在现代Web开发中,电商订单系统作为最常见且最复杂的业务场景之一,对前端技术的依赖度极高。随着移动端访问比例持续上升,CSS响应式布局和动画效果成为不可或缺的技能。然而,在学习和实践中,很多初学者和零基础开发者常因概念模糊或错误实现而导致功能异常或体验不佳。本文将围绕这一具体业务场景,深入剖析过程中常遇到的“反模式”案例。针对这些常见错误进行分析并给出修正方案,帮助读者避免踩坑、提升代码质量和用户体验。

后台模板 181

自动化运维-03Jenkins 构建环境排查

mvn help:effective-settings mvn -X clean package

weixin_52568278的博客 228

副队长Vue3教程(24)--Vue父子组件通信方案汇总对比

本文系统梳理了Vue中父子组件通信的三种方式:props(父→子数据传递)、defineEmits(子→父事件通知)、defineExpose(父主动调用子组件方法)。通过对比表与场景化选型,强调优先使用props和emit,仅在需触发一次性动作且不便用状态控制时考虑defineExpose。重点提醒避免滥用defineExpose,坚守单向数据流原则,提升组件解耦性与可维护性。

编程副队长 544

GitHub 日榜趋势速报 | 2026-11-27

GitHub 日榜 2026-11-27:orca、VIctory-Belobug-AMD、portwatch-vi 等 20 个开源项目 24 小时 Star 增速领先,每日更新的开源趋势速报。

wfly blog 97

雪花 ID 七个假设逐个验证:无锁测不出重号,JS 精度差 512

单线程 134.1-167.9 万 ids/s 零重号,但无锁的"零重号"是假安全感:放大竞争窗口后 4 线程 8000 个号重号 5719(71.5%),序列号只出现 138 种。8 线程加锁慢 4.1 倍。1970 纪年的 ID 是 2^53 的 834.6 倍,转 double 后 99.8% 变值、最大偏差 512;2026 纪年仍有 93.7% 变值、只够用 24.86 天。

CCbleach的专栏 261

Python 爬虫扩展篇(一):APP 抓包与 JS 逆向入门——从看见流量到读懂签名

APP 抓包(mitmproxy / Charles 配置与 Android 7+ 证书策略)、SSL Pinning 的识别与合法测试环境下的处理思路、JS 逆向定位签名参数的四种核心方法、Python 本地复现。

810cheng 451

SoduWork 项目测评初体验

这次排查的路径是「运行 → 异常行为 → 源码 → 修复 → 再运行验证」,而不是「通读源码找问题」。实测那条 200 响应的价值在于:它把三个原本各看各合理的文件钉在了一条因果链上,也让空口令短路、PBKDF2 随机 salt 导致等式探测失效这类"不跑就想不到"的坑提前暴露出来。文中提到的所有源码位置均来自 Fork 仓库的分支,欢迎对照阅读。SoduWork · 让 AI 的能力成为企业的生产力。

Nothing 341

基于Spring Boot和Vue的客服工单质检与知识推荐系统设计与实现

介绍工单受理和解决、关键词示例质检、结果复核与知识采纳反馈,并给出 Spring Boot、Vue 和 H2 环境的本地启动方法。

weixin_63587281的博客 246
上一篇: 【转】用openssl编写ssl,tls程序实例
下一篇: The Linux man-pages project
excpp
博客等级 码龄15年 0粉丝 61原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址