使用 nohup 实现持久化后台任务

nohup 结合重定向与后台运行符号可确保任务持续执行:
nohup your_command > output.log 2>&1 &
标准输出和错误均重定向至同一日志文件,末尾的 & 使命令在后台运行。

资源监控与自动重启

通过 crontab 定期检查进程状态并重启失效任务:

* * * * * pgrep -f "your_command" || nohup your_command > output.log 2>&1 &

每分钟检查进程是否存在,不存在则重新启动。可根据任务重要性调整检查频率。

限制资源使用

通过 ulimitcpulimit 控制资源:

nohup cpulimit -l 50 -- your_command > output.log 2>&1 &  

限制 CPU 使用率为 50%,避免单个任务耗尽资源。内存限制可通过 ulimit -v 实现。

日志轮转管理

使用 logrotate 防止日志文件过大:

/path/to/output.log {
    daily
    rotate 7
    compress
    missingok
}

每日轮转日志,保留7个压缩版本,避免磁盘空间被占满。

进程组隔离

通过 setsid 创建独立会话组:
setsid nohup your_command > output.log 2>&1 &
防止终端关闭或用户注销导致进程被终止,增强稳定性。

网络容错处理

对于网络依赖型任务,添加自动重连逻辑:

while true; do
    nohup your_network_command > output.log 2>&1
    sleep 10
done &

任务失败后等待10秒自动重启,适合边缘节点的不稳定网络环境。

更多推荐