zoukankan      html  css  js  c++  java
  • 在Linux中将脚本做成系统服务

      有一些情况下,我们需要将某些脚本作为系统服务来运行。比如,在我使用workerman框架开发php程序时,需要使用管理员权限来运行,而且需要开机自行启动程序提供服务。这个时候将启动程序写成服务就可以很方便使用了,而且在使用时也可以直接sudo service xxxx start,不需要手动敲出来复杂的文件路径。(在不使用小技巧的时候可能要这样做: sudo php /path/to/file start -d)生命苦短,多用些小技巧可能提高我们生命的效率,呵呵扯远了。我们直接来看如何自己写一个,并将之作为系统服务,且开机自动运行。

      首先,作为服务我们通常需要以下的功能:{start|stop|restart|status},接下来我就使用一段简单的bash脚本做一个演示:

      1.编辑我们的脚本文件

      vim myservice

      脚本内容:

      

    #!/bin/bash
    #
    #description: a demo
    #chkconfig:2345 88 77
    lockfile=/var/lock/subsys/myservice
    touch $lockfile
    # start 
    start(){
            if [ -e $lockfile ] ;then
                    echo "Service is already running....."
                    return 5
            else
                    touch $lockfile
                    echo "Service start ..."
                    return 0
            fi
    }
    #stop
    stop(){
            if [ -e $lockfile ] ; then
                    rm -f $lockfile
                    echo "Service is stoped "
                    return 0
            else
                    echo "Service is not run "
                    return 5
            fi
    
    }
    #restart 
    restart(){
            stop
            start
    }
    usage(){
            echo "Usage:{start|stop|restart|status}"
    }
    status(){
            if [ -e $lockfile ];then
                    echo "Service is running .."
                    return 0
            else
                    echo "Service is stop "
                    return 0
            fi
    }
    case $1 in
    start)
            start
            ;;
    stop)
            stop
            ;;
    restart)
            restart
            ;;
    status)
            status
            ;;
    *)
            usage
            exit 7
            ;;
    esac
    

      

      之后,我们将脚本复制至/etc/init.d文件夹中

      #cp myservice /etc/init.d

      将我们的myservice.sh添加至chkconfig

      #chkcofig --add myservice

      这样,在2345的运行级别下,myservice就会开机自动开启服务了,我们在任意目录下面都可以直接运行脚本 service myservice start

  • 相关阅读:
    HTTP协议
    OSI层次关系
    Python之web框架
    数据操作,流程控制语句
    Django简介
    函数
    2017java预留作业 1502 程逸飞
    2017java 预留作业2
    python django 项目支付
    如果注册xadmin出现了这个错误
  • 原文地址:https://www.cnblogs.com/jixingke/p/6050570.html
Copyright © 2011-2022 走看看