systemctl 启动服务在 SPEC 文件中不起作用

systemctl start service does not work in SPEC file

我遇到了一个问题,我的 SPEC 文件中的命令 "sudo systemctl start xxx.service" 在升级我的 RPM 包时不起作用,以下是我在 SPEC 文件中的 %post 脚本,

%post
echo "---------------------------- post  -------------------------------"
# refresh installation
if [  == 1 ]; then
  sudo echo "Installation finished."
# upgrade installation
elif [  -gt 1 ]; then
  sudo echo "Starting service xxx.service..."
  sudo /usr/bin/systemctl enable xxx.service > /dev/null 2>&1
  sudo /usr/bin/systemctl start xxx.service
  sleep 10
  sudo echo "Finished."
fi
exit 0

我确定服务文件已经存在于目录 /usr/lib/systemd/system 中,我可以使用命令 "sudo systemctl start xxx.service".

手动启动它

而且我发现 "sleep 10" 命令也不起作用。

如果对此问题有任何建议,非常感谢。

几个问题:

  • 您不应该在 scriplets 中使用 sudo,因为 1) 它可能未安装 2) rpm 安装仍然以超级用户身份运行
  • 您应该使用标准 RPM macros for SystemD 而不是重新发明轮子。

基本上可以简单地归结为:

%{?systemd_requires}
BuildRequires: systemd

# ...

%post
%systemd_post %{name}.service

%preun
%systemd_preun %{name}.service

%postun
%systemd_postun_with_restart %{name}.service

# ...

请注意 CentOS/RHEL 的 SystemD 宏位于 systemd 包中,而在 Fedora 中它们现在位于 systemd-rpm-macros.

将服务启动命令放在脚本“%posttrans”中解决了我的问题,感谢您的所有建议。