linux开机启动

在开发过程中,遇到了需要开机启动某个后台程序,总结如下几个方法:

一. /etc/rc.local

  1. 编辑此文件,在文件末尾添加要启动的程序
  2. chmod +x /etc/rc.local 

   开机重启测试

 

二. /etc/init.d/

  1. 在该目录下编辑脚本文件,如test.sh文件
#!/bin/sh

### BEGIN INIT INFO
# Provides:       ceph ceph-mon ceph-osd
# Required-Start: $network $remote_fs
# Required-Stop:  $network $remote_fs
# Default-Start:  3 5
# Default-Stop:   0 1 2 6
# Short-Description: Ceph is a distributed object, and block, storage platform
# Description:    Ceph is a distributed object, block, and file storage platform
### END INIT INFO

case "$1" in
    start)
        /usr/bin/python /usr/local/bin/daemon.py &
        ;;
    stop)
        killall python
        killall python
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

  注意:此文件一定要写 start/restart/stop 函数,否则会测试失败

       2. 创建链接

        update-rc.d test.sh defaults

       3. 查看是否成功

         service --status-all | grep test

         如有结果,表示成功。  

       原理:linux 启动会先执行 /etc/inittab,然后分别执行/etc/rcS.d/目录下的程序,然后是/etc/rcN.d下的程序。从小到大依次执行

       取消开机启动:update-rc.d -f test.sh remove

 

三.systemd方式

     systemd是无关于平台的,目前共有三种系统管理工具,如Ubuntu的upstart,和sysvint及systemd 工具。现在systemd逐渐占据主导地位。但它实在太复杂,这里只是如何快速使用它进行了说明,具体请搜索相关信息。   

  • 创建service 文件

      

[Unit]
Description= test service[Service]
User=root
Group=root
Type=simple
ExecStart=/usr/local/bin/test.sh

[Install]
WantedBy=multi-user.target

 

  •  执行命令
    sudo systemctl enable test.service #创建链接 /etc/systemd/system/multi-user.target.wants/test.service  --> /etc/systemd/system/test.service
  •  执行命令

              sudo systemctl start test.service

              

     

     查看是否成功:systemctl list-dependencies multi-user.target  | grep test  ,如果有表示成功

     取消开机启动:systemctl disable test.service

 

四.命令对比systemd 和sysvint

     systemctl start x.service <<==>> service start x

     systemctl stop x.service <<==>> service stop x

     systemctl restart x.service <<==>> service restart x

     systemctl status x.service <<==>> service status x

                          .........................                 

 

     sysvinit 的开机runlevel 类似于 systemd 中target的概念,target是一组服务的集合。

     systvinit 中的 目录/etc/init.d 类似于systemd 中的 /lib/systemd/system.

     而/etc/init.d/rcN.d/则类似于 /etc/systemd/system

     再一个要说明是systemd 也对sysvinit进行了兼容,也就是原来你用sysvinit的方式的服务,也不会受到影响。

 

posted @ 2019-02-18 22:11  雅|望|天|堂  阅读(198)  评论(0)    收藏  举报