在Ruby中使用双叉创建守护程序 [英] Create a daemon with double-fork in Ruby

查看:55
本文介绍了在Ruby中使用双叉创建守护程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中创建行为良好的Unix或Linux守护程序的正确方法是什么?

井的定义是什么?行为正常的守护程序,以及如何用Ruby编写这样的程序?

What is the definition of a well-behaved daemon anyway, and how would one write such a program in Ruby?

推荐答案

根据Stevens的高级编程UNIX环境》第13章,这是制作行为良好的Unix守护程序的过程:

According to Stevens's Advanced Programming in the UNIX Environment chapter 13, this is the procedure to make a well-behaved Unix daemon:


  1. Fork并有一个父级出口。这使Shell或引导脚本认为命令已完成。此外,保证子进程不会成为进程组负责人(下一个setsid的先决条件)

  2. 调用 setsid 创建一个新会议。这会做三件事:

  1. Fork and have the parent exit. This makes the shell or boot script think the command is done. Also, the child process is guaranteed not to be a process group leader (a prerequisite for setsid next)
  2. Call setsid to create a new session. This does three things:

  1. 该流程成为新会话的会话负责人

  2. 该流程成为流程组新流程组的负责人

  3. 该流程没有控制终端


  • (可选)再次分叉并有父母出口。这可以确保守护程序不是会话领导者,也不可以获取控制终端(在SVR4下)

  • 将当前工作目录更改为 / 避免干扰安装和卸载

  • 将文件模式创建掩码设置为000,以允许以后创建具有所需权限的文件。

  • 关闭从父级继承的不需要的文件描述符(反过来也没有控制终端): stdout stderr stdin

  • Optionally fork again and have the parent exit. This guarantes that the daemon is not a session leader nor can it acquire a controlling terminal (under SVR4)
  • Change the current working directory to / to avoid interfering with mounting and unmounting
  • Set file mode creation mask to 000 to allow creation of files with any required permission later.
  • Close unneeded file descriptors inherited from the parent (there is no controlling terminal anyway): stdout, stderr, and stdin.
  • 如今,有一个文件可以跟踪Linux大量使用的PID分发启动脚本。请确保写出孙子的PID,即第二个fork的返回值(步骤3)或步骤3之后的 getpid()值。

    Nowadays there is a file to track the PID which is used heavily by Linux distribution boot scripts. Be sure to write out the PID of the grandchild, either the return value of the second fork (step 3) or the value of getpid() after step 3.

    这里是一个Ruby实现,主要是从书中翻译过来的,但是带有双叉并写出了守护进程PID。

    Here is a Ruby implementation, mostly translated from the book, but with the double-fork and writing out the daemon PID.

    # Example double-forking Unix daemon initializer.
    
    raise 'Must run as root' if Process.euid != 0
    
    raise 'First fork failed' if (pid = fork) == -1
    exit unless pid.nil?
    
    Process.setsid
    raise 'Second fork failed' if (pid = fork) == -1
    exit unless pid.nil?
    puts "Daemon pid: #{Process.pid}" # Or save it somewhere, etc.
    
    Dir.chdir '/'
    File.umask 0000
    
    STDIN.reopen '/dev/null'
    STDOUT.reopen '/dev/null', 'a'
    STDERR.reopen STDOUT
    

    这篇关于在Ruby中使用双叉创建守护程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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