以守护程序形式运行Redis并使用Upstart来管理它不起作用

时间:2011-12-29 23:43:05

标签: redis daemon upstart

我为Redis编写了一个Upstart脚本,如下所示:

description "Redis Server"

start on runlevel [2345]
stop on shutdown
expect daemon

exec sudo -u redis /usr/local/bin/redis-server /etc/redis/redis.conf

respawn
respawn limit 10 5

然后我通过它的redis.conf配置redis到:

daemonize yes

所有文档和我自己的实验都表示Redis以守护进程形式分叉两次并且“expect daemon”应该可以工作,但Upstart脚本始终保持前父级的PID(PID - 1)。有人有这个工作吗?

2 个答案:

答案 0 :(得分:6)

以下暴发配置似乎对我有用,在ubuntu 12.04上使用upstart 1.5,并将redis.conf daemonize设置为yes:

description "redis server"

start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown

setuid redis
setgid redis
expect fork

exec /opt/redis/redis-server /opt/redis/redis.conf

respawn

答案 1 :(得分:3)

其他人也有同样的问题。请参阅this gist

当激活daemonize选项时,Redis不会检查进程是否已经是守护进程(没有调用getppid)。它系统地分叉,但只有一次。这有点不寻常,其他守护进程机制可能需要对getppid进行初始检查,并且fork被调用两次(在setsid调用之前和之后),但在Linux上并不是严格要求的。

有关守护进程的详细信息,请参阅this faq

Redis daemonize功能非常简单:

void daemonize(void) {
    int fd;

    if (fork() != 0) exit(0); /* parent exits */
    setsid(); /* create a new session */

    /* Every output goes to /dev/null. If Redis is daemonized but
     * the 'logfile' is set to 'stdout' in the configuration file
     * it will not log at all. */
    if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
        dup2(fd, STDIN_FILENO);
        dup2(fd, STDOUT_FILENO);
        dup2(fd, STDERR_FILENO);
        if (fd > STDERR_FILENO) close(fd);
    }
}

Upstart文档说:

expect daemon
Specifies that the job's main process is a daemon, and will fork twice after being run.
init(8) will follow this daemonisation, and will wait for this to occur before running
the job's post-start script or considering the job to be running.
Without this stanza init(8) is unable to supervise daemon processes and will
believe them to have stopped as soon as they daemonise on startup.

expect fork
Specifies that the job's main process will fork once after being run. init(8) will
follow this fork, and will wait for this to occur before running the job's post-start
script or considering the job to be running.
Without this stanza init(8) is unable to supervise forking processes and will believe
them to have stopped as soon as they fork on startup.

所以我要么在Redis端停用守护进程,要么尝试在upstart配置中使用expect fork而不是期望守护进程。