【问题标题】:Linux daemon start upLinux 守护进程启动
【发布时间】:2012-08-01 11:50:22
【问题描述】:

我在 linux(Redhat Server Edition 5.1) 上编写了一项服务。它由 shell 脚本启动, 如果我启动我的应用程序我手动启动我的服务,现在我想在启动时启动我的服务,这意味着我通过我的守护进程将我的服务放在 init.d 文件夹中,而不是在启动时调用,任何人都知道如何启动linux 启动时的守护进程?

这是我的示例,但不起作用

#!/bin/sh
#
# myservice     This shell script takes care of starting and stopping
#               the <myservice>
#

# Source function library
. /etc/rc.d/init.d/functions


# Do preliminary checks here, if any
#### START of preliminary checks #########


##### END of preliminary checks #######


# Handle manual control parameters like start, stop, status, restart, etc.

case "$1" in
  start)
    # Start daemons.

    echo -n $"Starting <myservice> daemon: "
    echo
    daemon <myservice>
    echo
    ;;

  stop)
    # Stop daemons.
    echo -n $"Shutting down <myservice>: "
    killproc <myservice>
    echo

    # Do clean-up works here like removing pid files from /var/run, etc.
    ;;
  status)
    status <myservice>

    ;;
  restart)
    $0 stop
    $0 start
    ;;

  *)
    echo $"Usage: $0 {start|stop|status|restart}"
    exit 1
esac

exit 0

【问题讨论】:

    标签: linux linux-kernel daemon redhat


    【解决方案1】:

    将 2 个 cmets 放入您的脚本中:

    # chkconfig: - 90 10
    # description: description of your service
    

    以 root 身份运行:

    chkconfig --add my_service
    

    【讨论】:

    • 会发生什么在该脚本中添加了两个注释行,我无法理解您,
    • 这些行将告诉 chkconfig 您的脚本应该在哪个运行级别运行,以及启动和停止优先级。看到这个:linux.die.net/man/8/chkconfig
    • 如果该服务已经列出,您可能需要在执行 --add 之前运行 chkconfig --del my_service
    【解决方案2】:

    一个基本的 unix 守护进程执行以下操作:

    fork
    close all filedescriptors (stdout,stderr, etc)
    chdir /
    signal handeling (sighup, sigterm etc)
    while
    do stuff
    sleep(xx)
    done
    

    (C 中的示例:daemon.c)

    关于如何安装启动脚本的 Red Hat 示例:

    要在 redhat 系统启动时启动一个守护进程,您需要一个 init 脚本。 它应该放在 /etc/init.d

    初始化脚本示例:

    代码:

    # chkconfig: 3 99 1
    # description: my daemon
    
    case "$1" in
    'start')
    /usr/local/bin/mydaemon
    ;;
    
    'stop')
    pkill mydaemon
    ;;
    
    'restart')
    pkill -HUP mydaemon
    ;;
    
    esac
    

    第一行将告诉 chkconfig 在运行级别 3 中以优先级 99 启动守护进程,并在服务器关闭时将其作为优先级 1 终止。

    要安装启动脚本,请使用以下命令:chkconfig --add ./scriptabove 现在它将在服务器启动时启动。

    要立即启动它,请使用:service start

    如果您想了解更多详细信息,请访问a link

    希望这会有所帮助!

    【讨论】:

    • 但是当我像这样添加我会得到一个错误,检查配置不支持
    【解决方案3】:

    不同的 linux 发行版包含不同的服务管理工具。你应该看看launchdOpenRC(出现在Gentoo)和SystemD(比如Arch)

    希望这会有所帮助:)

    【讨论】:

    • 啊,我没有看到它是特定于 RedHat 的。无论如何,我会把我的答案留给未来的读者。
    • Nitpick:正如您链接到的页面上所指出的那样,它是“systemd”(没有大写)。此外,systemd 与 Fedora、Arch、Mageia、Mandriva、openSUSE、Chakra、NixOS 和 Frugalware 一起提供。它在 Debian 和 Gentoo 上可用(但不是默认的 init 系统)。然而,launchd 似乎只在 Mac OS X 上使用,另见 en.wikipedia.org/wiki/Launchd
    【解决方案4】:

    chkconfig --add your_service_name

    【讨论】: