使用Supervisor制作Linux的系统服务


#Linux#


2014-05-16

Supervisor是一个进程控制工具,一般作为系统service运行,不过它可以管理其他进程,让其他进程一直在后台运行。该工具可以在大多数Linux发行版中使用。下面说一下如何在ubuntu下安装、配置和使用。笔者使用的Linux Mint 16。

安装

sudo apt-get install supervisor

安装完成后,可以使用service命令管理supervisor,例如:

sudo service supervisor start
sudo service supervisor stop

supervisor相关的是两个程序,一个是daemon程序supervisord,另外一个是程序管理工具supervisorctl

配置文件

其配置文件在目录/etc/supervisor中,该目录下有以下文件:

bash >> ls
conf.d  supervisord.conf

看一下supervisord.conf中的内容:

; supervisor config file

[unix_http_server]
file=/var/run/supervisor.sock   ; (the path to the socket file)
chmod=0700                       ; sockef file mode (default 0700)

[supervisord]
logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log)
pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
childlogdir=/var/log/supervisor            ; ('AUTO' child log dir, default $TEMP)

; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL  for a unix socket

; The [include] section can just contain the "files" setting.  This
; setting can list multiple files (separated by whitespace or
; newlines).  It can also contain wildcards.  The filenames are
; interpreted as relative to this file.  Included files *cannot*
; include files themselves.

[include]
files = /etc/supervisor/conf.d/*.conf

我们重点关注最后两行内容:

[include]
files = /etc/supervisor/conf.d/*.conf

这意味着要添加新的程序的话,既可以在supervisord.conf文件中添加,也可以在conf.d目录下添加以.conf为后缀的文件。

示例

启动supervisor:

sudo service supervisor start

编写程序:

sudo vim /home/test.py

加入以下内容:

import time
import os

while True:
    time.sleep(6)
    os.system("date >> /home/date.txt")

编写supervisor配置文件:

sudo vim /etc/supervisor/conf.d/test.conf

加入以下内容:

[program:test]
command = python /home/test.py
autostart = true
user = root

command指定运行的命令,autostart指定是否在supervisor启动时自动运行该命令,user指定以哪个用户运行命令。还有其他参数来实现丰富的功能,例如指定日志输出位置,这里不做说明,具体请参考Adding a Program in supervisor

现在可以重启supervisor或者使用以下命令更新配置:

sudo supervisorctl update

test.py应该会自动运行,如果没有运行请执行以下命令:

sudo supervisorctl start test

过一会后关闭该test.py:

sudo supervisorctl stop test

在date.txt中可以看到一下内容:

2014年 05月 15日 星期四 19:34:26 CST
2014年 05月 15日 星期四 19:34:32 CST
2014年 05月 15日 星期四 19:34:38 CST
2014年 05月 15日 星期四 19:34:44 CST
2014年 05月 15日 星期四 19:34:50 CST
2014年 05月 15日 星期四 19:34:56 CST
2014年 05月 15日 星期四 19:35:02 CST
2014年 05月 15日 星期四 19:35:08 CST

更多内容请访问官网:supervisor


( 本文完 )