为什么运行 `systemctl start; 时退出状态不同? systemctl is-active` 和 `systemctl is-active` 分别吗?

为什么运行 `systemctl start; 时退出状态不同? systemctl is-active` 和 `systemctl is-active` 分别吗?

以下序列给出了第一个命令的返回值,而不是我预期的第二个命令的返回值(无论我是否在子 shell 中运行第一个命令):

sudo systemctl start x; sudo systemctl is-active --quiet x; echo $?;
(sudo systemctl start x); sudo systemctl is-active --quiet x; echo $?;

该服务x已损坏并且无法启动 - 所以他没有运行。以下命令独立运行,给出了正确的返回值3

sudo systemctl is-active --quiet x; echo $?;

0那么,为什么我在运行时得到的是第一个命令 ( ) 的返回值,而不是第二个命令的command; command; echo $?返回值 ( )呢?3echo $?

我上线了GNU bash, version 4.4.12(1)-release (x86_64-pc-linux-gnu)。我知道,如果我将它分成两行,它就会起作用:

sudo systemctl start x;
sudo systemctl is-active --quiet x; echo $?;

但我需要将它作为一行,因为我将它放入 PHPshell_exec()函数中。运行两次shell_exec()与将命令放在一行中的结果相同。

答案1

当我遇到这样的问题时,我倾向于遵循福尔摩斯的口头禅,并考虑一旦不可能的事情被消除后,剩下的事情,无论多么难以置信。当然,对于计算机来说,没有什么是不可能的,但是有些事情太不可能了,我们一开始就可以忽略它们。 (这与原标题更有意义,“ command; command; echo $?——返回值不正确,为什么?”)

在这种情况下,如果

sudo systemctl start x; sudo systemctl is-active --quiet x; echo $?;

显示为$?0,说明systemctl is-active确实表示成功。单独systemctl is-active显示该服务未激活的事实强烈表明该服务与键入命令的操作员之间存在竞争;基本上,服务确实启动到足以systemctl start完成、systemctl is-active运行并发现服务处于活动状态,但随后服务失败,因此人工输入systemctl is-active发现它处于非活动状态。

systemctl start在和之间添加短暂的延迟systemctl is-active应该可以避免误报。

答案2

Systemd 会在短时间内(0.1几秒)启动服务,然后服务崩溃。

返回3应有的样子;

sudo systemctl start x; sleep 0.2; sudo systemctl is-active --quiet x; echo $?;

不到0.2几秒,它就返回了,0因为它不应该是这样:

sudo systemctl start x; sleep 0.1; sudo systemctl is-active --quiet x; echo $?;

如果我这样做的话,systemctl start x; ps -fA | grep -i x我也会看到这项服务。如果我ps之后再跑,它就消失了。

答案3

尝试这个:

sudo systemctl start x && sudo systemctl is-active --quiet x; echo $?;

仅当前一个命令成功完成时,才会&&强制系统按顺序运行命令。

相关内容