〖Linux〗以后台方式启动/结束指定程序/命令(不受 exit 或点击窗口关闭按钮等终端退出操作的影响)...

#!/bin/bash - 
#===============================================================================
#
#          FILE: bgcmd
# 
#         USAGE: 方式1 -- $ ./bgcmd             # 启动指定后台程序
#                方式2 -- $ ./bgcmd off         # 结束指定后台程序
# 
#   DESCRIPTION: 后台运行程序/命令(类似于deamon进程)
# 
#       OPTIONS: ---
#  REQUIREMENTS: >> 按需要修改 cmd 和 need_root 这两个变量<<
#          BUGS: ---
#         NOTES: ---
#        AUTHOR: linkscue(scue),
#  ORGANIZATION: 
#       CREATED: 2013年08月14日 22时04分38秒 HKT
#      REVISION:  ---
#===============================================================================

get_process(){
    cmd="$1"
    ps aux | grep -v 'grep' | grep "$cmd" | awk '{print $2}'
}

kill_process(){
    exist="$1"
    if [[ "$need_root" != "" ]]; then
        sudo kill $exist
    else
        kill $exist
    fi
    echo "process [ $(echo $exist) ] had killed."
}

#-------------------------------------------------------------------------------
#  cmd: 希望在后台执行的程序/命令
#  need_root: 是否需要root权限执行
#-------------------------------------------------------------------------------
need_root=true
cmd="python -m SimpleHTTPSever 80"

# get root, if need.
if [[ "$need_root" != "" ]]; then
    sudo ls > /dev/null
    ret=$?
    if [[ $ret != 0 ]]; then
        echo "can't get root, exit."
        exit 1
    fi
fi

# run cmd
exist=$(get_process "$cmd")
if [[ "$1" != "" ]] ; then                      # kill process
    kill_process "$exist"
else
    if [[ "$exist" != "" ]]; then
        kill_process "$exist"
    fi
    if [[ "$need_root" != "" ]]; then
        sudo nohup $cmd >/dev/null 2>&1 &       # run as root
    else
        nohup $cmd > /dev/null 2>&1 &           # run as other
    fi
    sleep 0.1
    exist=$(get_process "$cmd")
    echo "run [ $(echo $exist) ] at background."
fi

 

你可能感兴趣的:(〖Linux〗以后台方式启动/结束指定程序/命令(不受 exit 或点击窗口关闭按钮等终端退出操作的影响)...)