首页/系统/Linux 运维命令速查/场景:后台任务守护与日志
进程与作业69 条

场景:后台任务守护与日志

没有 systemd 权限时的标准后台化组合:nohup + setsid + 重定向 + pidfile,一条命令交代清楚「在哪跑、日志在哪、怎么停」。

Linux 运维命令速查系统更新于 2026-10-12
场景临时常驻任务(爬虫/同步/计算)
组合nohup + setsid + 重定向 + $!/pidfile

标准启动

标准启动
cd /opt/app
nohup setsid ./worker.sh --mode sync </dev/null >> /var/log/worker.log 2>&1 &
echo $! > /run/worker.pid
cat /run/worker.pid; ps -p $(cat /run/worker.pid) -o pid,etime,cmd

停止与核对

停止与核对
kill $(cat /run/worker.pid)
sleep 2; ps -p $(cat /run/worker.pid) || echo stopped
rm -f /run/worker.pid
更正规的路:写进 systemd(Restart=on-failure、StandardOutput=append:...),让守护与日志交给系统。

易错点

  • >> 与 > 区别:重启任务用 > 清空日志会丢历史,用 >> 追加(配 logrotate 更佳)
  • 进程崩溃后 nohup 不会拉起:写个每分钟检测 pidfile 的轻量 cron 也是一种土办法(或用 systemd)

数据来源与参考

  • man 1 nohup(GNU coreutils 手册)

相关工具

​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌