Node.JS 父进程 ID [英] Node.JS Parent Process ID

查看:61
本文介绍了Node.JS 父进程 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 Node.JS 获取父进程 ID?我想检测父母是否以无法通知孩子的方式被杀死或失败.如果发生这种情况,子进程的父进程 id 应该变为 1.

Is it possible to get the parent process-id using Node.JS? I would like to detect if the parent is killed or fails in such a way that it cannot notify the child. If this happens, the parent process id of the child should become 1.

这比要求父级定期发送保持活动信号更可取,也比运行 ps 命令更可取.

This would be preferable to requiring the parent to periodically send a keep-alive signal and also preferable to running the ps command.

推荐答案

您可以使用 pid-file.类似的东西

You can use pid-file. Something like that

var util = require('util'),
    fs = require('fs'),
    pidfile = '/var/run/nodemaster.pid';

try {
    var pid = fs.readFileSync(pidfile);
    //REPLACE with your signal or use another method to check process existence :)
    process.kill(pid, 'SIGUSR2'); 
    util.puts('Master already running');
    process.exit(1);
} catch (e) {
    fs.writeFileSync(pidfile, process.pid.toString(), 'ascii');
}

//run your childs here

您也可以在 spawn() 调用中将 pid 作为参数发送

Also you can send pid as argument in spawn() call

这篇关于Node.JS 父进程 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆