systemd服务配置是最可靠方式,通过type=oneshot与execstartpost调用绝对路径shutdown命令实现进程结束自动关机;shell脚本+wait适用于临时任务但需防终端中断;at命令适合不可修改的第三方进程,精度秒级。

麒麟系统中,当某个关键进程(如数据处理脚本、编译任务或备份程序)运行完成时,需要系统立即关机以节省电力或进入无人值守状态,不能依赖人工监控进程结束再手动关机。
用systemd服务配置“进程结束后自动关机”
这是最可靠的方式,利用systemd的`Type=oneshot`特性与`ExecStartPost`钩子,在主进程退出后立刻触发关机,全程由系统守护进程管理,不依赖终端会话存活。
第一步:创建用户级service文件
执行命令:mkdir -p ~/.config/systemd/user && nano ~/.config/systemd/user/finish-shutdown.service
第二步:填入以下内容,注意【Type必须为oneshot,且ExecStartPost必须使用绝对路径的shutdown命令】——若写成shutdown或未加sudo,将因权限或PATH缺失而静默失败。
[Unit]<br>Description=运行完mytask.sh后关机<br>After=network.target<br><br>[Service]<br>Type=oneshot<br>ExecStart=/usr/local/bin/mytask.sh<br>ExecStartPost=/usr/bin/sudo /sbin/shutdown --poweroff now<br>RemainAfterExit=no<br>User=kylin<br>Group=kylin<br><br>[Install]<br>WantedBy=default.target
第三步:启用linger并加载服务loginctl enable-linger $USER→systemctl --user daemon-reload→systemctl --user enable --now finish-shutdown.service
第四步:验证逻辑是否成立
手动启动该服务:systemctl --user start finish-shutdown.service→等待mytask.sh执行完毕→观察系统是否在3秒内开始关机流程。若未关机,检查journal:systemctl --user journal -u finish-shutdown.service,重点看ExecStartPost行是否报“Operation not permitted”——这说明sudo未配置免密或/usr/bin/sudo路径错误。
用shell脚本+wait机制实现进程结束即关机
适用于无法改写为systemd服务的临时任务,比如直接运行Python脚本或Makefile构建,要求脚本本身可控、不后台化。
方法一:编写包装脚本
执行:sudo nano /usr/local/bin/run-and-poweroff.sh,内容如下:
#!/bin/bash<br>/usr/local/bin/mytask.sh<br>if [ $? -eq 0 ]; then<br> /sbin/shutdown --poweroff now<br>else<br> logger "mytask.sh failed, not shutting down"<br>fi
赋予执行权限:
sudo chmod +x /usr/local/bin/run-and-poweroff.sh
方法二:前台运行并阻塞等待
直接在终端中执行:bash /usr/local/bin/run-and-poweroff.sh。这一步操作起来很简单,直接把脚本路径填进去就行。但注意:该方式要求终端保持打开,若关闭终端窗口,脚本会被SIGHUP中断,关机不会触发。
方法三:脱离终端后台运行(慎用)
执行:nohup /usr/local/bin/run-and-poweroff.sh > /dev/null 2>&1 &。⚠️提醒:【nohup方式下,shutdown可能因缺少tty而被systemd拒绝执行,需提前配置sudoers允许该用户无密码调用shutdown】,否则日志里只显示“Failed to set wall message, ignoring: Access denied”。
用at命令在进程末尾精准调度关机
适合已知进程耗时稳定、且不允许脚本修改的场景,例如调用第三方闭源工具后必须关机,又不能动它的启动逻辑。
① 创建带at调度的包装器:sudo nano /usr/local/bin/trigger-at-shutdown.sh
内容为:
#!/bin/bash<br>/usr/local/bin/mytask.sh<br>echo "/sbin/shutdown --poweroff now" | at now
② 赋予执行权限:sudo chmod +x /usr/local/bin/trigger-at-shutdown.sh
③ 确保atd服务已启用:sudo systemctl enable --now atd。若系统未安装at,先运行sudo apt install at -y。
④ 执行包装器:sudo /usr/local/bin/trigger-at-shutdown.sh。at会在mytask.sh返回后立即提交关机任务,精度达秒级,且不依赖当前shell生命周期。











