延长 systemd“启动”状态,直到进程的内部状态准备好

延长 systemd“启动”状态,直到进程的内部状态准备好

当你用systemd启动一个服务时,进程只处于该activating状态一段时间。active一旦该过程成功启动,它就会转变为。

但是,如果我有一项复杂的服务需要一段时间才能准备好怎么办?如何延长activating状态直到服务在内部准备就绪?

答案1

[Service]您的单位部分中,添加(或更改)Type=notify

这告诉 systemd 进程本身将在启动时发出信号。因此,当进程启动时,systemd 不会假设它已准备好。

为此,该流程必须实施sd_通知(3)


下面是 C 语言通知服务的最小示例:

# notifier.service
[Service]
Type=notify
ExecStart=%h/bin/notifier
/* main.c */
#include <systemd/sd-daemon.h>
#include <unistd.h>

int main(void) {
        /* Sleep to emulate 10s bootup time */
        /* Expect status 'activating (start)' during this */
        /* `systemctl start`, will block */
        sleep(10);

        /* Send a signal to say we've started */
        sd_notify(0, "READY=1");

        /* Units which are After= this unit will now start */
        /* `systemctl start` will unblock now */

        /* Sleep to emulate 10s run time */
        /* Expect status 'active (running)' during this */
        sleep(10);

        /* Send a signal to say we've started the shutdown procedure */
        sd_notify(0, "STOPPING=1");

        /* Sleep to emulate 10s shutdown */
        /* Expect status 'deactivating' during this */
        sleep(10);

        return 0;

        /* Expect status 'inactive (dead)' at this point */
}
# makefile
a.out: main.c
        gcc main.c -lsystemd

install: a.out notifier.service
        install -D a.out ~/bin/notifier
        install -D notifier.service ~/.config/systemd/user/notifier.service

相关内容