如何在ExecStop或ExecPostStop中访问服务的返回码?

时间:2018-08-31 07:38:01

标签: linux service centos7 systemd

是否有可能从正在运行的进程中捕获退出代码,例如ExecStart系统服务单位中?我想检查进程是否退出或是否发生错误。

阅读了systemd.servicesystemd.exec文档后,我认为$SERVICE_RESULT $EXIT_CODE和/或$EXIT_STATUS可能会有所帮助。但无济于事。

给出此测试单位:

[Unit]
Description=Testing Run Order

[Service]
Type=simple
Environment=HELLO=WORLD
ExecStartPre=/bin/echo [StartPre] $MAINPID $SERVICE_RESULT $EXIT_CODE $EXIT_STATUS
ExecStartPost=/bin/echo [StartPost] $MAINPID $SERVICE_RESULT $EXIT_CODE $EXIT_STATUS
ExecStart=/bin/sleep 2
ExecStop=/bin/env
ExecStop=/bin/echo [Stop] $MAINPID $SERVICE_RESULT $EXIT_CODE $EXIT_STATUS
ExecStopPost=/bin/echo [StopPost] $MAINPID $SERVICE_RESULT $EXIT_CODE $EXIT_STATUS

我得到以下输出:

Aug 30 08:37:26 localhost.localdomain systemd[1]: Starting Testing Run Order...
Aug 30 08:37:26 localhost.localdomain echo[3458]: [StartPre]
Aug 30 08:37:26 localhost.localdomain systemd[1]: Started Testing service metrics.
Aug 30 08:37:26 localhost.localdomain echo[3460]: [StartPost] 3459
Aug 30 08:37:27 localhost.localdomain env[3465]: LANG=en_US.UTF-8
Aug 30 08:37:27 localhost.localdomain env[3465]: PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
Aug 30 08:37:27 localhost.localdomain env[3465]: HELLO=WORLD
Aug 30 08:37:27 localhost.localdomain echo[3467]: [Stop]
Aug 30 08:37:27 localhost.localdomain echo[3469]: [StopPost]

没什么。我目前仍受systemd 219困扰(+ PAM +审计+ SELINUX + IMA -APPARMOR + SMACK + SYSVINIT + UTMP + LIBCRYPTSETUP + GCRYPT + GNUTLS + ACL + XZ -LZ4 -SECCOMP + BLKID + ELFUTILS + KMOD + IDN )在Centos7上。

2 个答案:

答案 0 :(得分:1)

$EXIT_CODE$EXIT_STATUS仅在systemd v232中添加。如果您坚持使用较旧的版本,则必须解决它,也许要使用类似的东西(未经测试):

ExitStart=/bin/sh -c '/* normal command goes here */; echo $? > /tmp/my-service.exit'
ExecStopPost=/bin/sh -c 'EXIT_STATUS=$(cat /tmp/my-service.exit); /* rest of command goes here */'

旁注:写类似的东西

ExecStop=/bin/echo [Stop] $MAINPID $SERVICE_RESULT $EXIT_CODE $EXIT_STATUS

在您的测试单元中,这些变量由systemd替换。要检查实际过程的环境,请使用外壳程序(如上)或类似env的命令(就像对ExecStop行之一所做的那样。)

答案 1 :(得分:1)

您实际上可以从命令new {title="Read more link", selector="p", classes="read-more-link" } // this allows user to add class to any p new {title="Read more link", selector="p > a", classes="read-more-link" } // this adds class to a tag new {title="Read more link", selector="p > a", classes="read-more-link", wrapper="true" } // this does nothing new {title="Read more link", selector="p > a", block="p", classes="read-more-link", wrapper="true" } // this does nothing new {title="Read more link", selector="a", block="p", classes="read-more-link", wrapper="true" } // this does nothing 读取ExecMainStatusCode

例如,如果您要根据结果(平稳停止或硬崩溃)触发命令,则可以使用以下命令:

systemctl show your_service --property=ExecMainStatus