SagerXiao's Blog

Restart of an old programmer

Python应用只启动一个进程

后台进程我们只希望运行一次,我们可以通过对pid进行控制进程仅启动一次,参考程序

Control one process
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os, sys

def lockPidFile(lockfile):
    pidfile = open(lockfile, 'a+')
    try:
        pid = pidfile.read()
        if pid is not None and len(pid.strip()) > 0:
            tmpfile = lockfile + ".tmp"
            os.system("ps -A|grep %s > %s" % (pid, tmpfile))
            tmp_size = os.path.getsize(tmpfile)
            os.remove(tmpfile)
            if (tmp_size > 0):
                return False

        pidfile.close()
        pidfile = open(lockfile, 'w')
        pidfile.write(str(os.getpid()))
        return True

    finally:
        pidfile.close()

    return False
1
2
3
4
5
6
7
8
def run():
    # run your application

if __name__ == "__main__":
    if not lockPidFile("/var/run/app.pid"):
        print "Another process is running."
        sys.exit(1)
    run()

有了PID文件和pid之后,对应用的起停就可以使用这个PID来实现,以下是服务启停的脚本参考

service start,stop,restart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/bin/bash
#
# chkconfig: - 85 15
app=/usr/bin/your-app
pidfile=/var/your-app.pid

case $1 in
    start)
        echo -n "Starting your app"
        nohup $app >/var/log/app-console.log 2>&1 &
        if [ $? != 0 ]; then
            echo
            echo "Your app startup failed, please see detail information\
                in '/var/log/app-console.log'."
            echo
        fi
        echo " done"
        ;;

    stop)
        echo -n "Stopping your app"
        kill -9 `cat $pidfile`
        echo " done"
        ;;

    restart)
        $0 stop
        $0 start
        ;;

    show)
        ps -ef|grep `cat $pidfile`
        ;;

    *)
        echo -n "Usage: $0 {start|restart|stop|show}"
        ;;

esac

Comments