要确保使用nohup命令启动的Linux进程在系统重启后自动启动,您可以使用以下方法之一:
systemd服务(推荐)创建一个新的systemd服务单元文件,例如/etc/systemd/system/my_service.service,并添加以下内容:
[Unit]
Description=My custom service
After=network.target
[Service]
Type=simple
User=<your_user>
WorkingDirectory=/path/to/working/directory
ExecStart=/usr/bin/nohup /path/to/your/script.sh > /path/to/output.log 2>&1 &
Restart=on-failure
[Install]
WantedBy=multi-user.target
替换<your_user>、/path/to/working/directory、/path/to/your/script.sh和/path/to/output.log为实际值。
然后运行以下命令以启用和启动服务:
sudo systemctl daemon-reload
sudo systemctl enable my_service.service
sudo systemctl start my_service.service
这将确保您的脚本在系统启动时自动运行,并在失败时自动重启。
cron的@reboot功能编辑用户的crontab文件:
crontab -e
在文件末尾添加以下行:
@reboot /usr/bin/nohup /path/to/your/script.sh > /path/to/output.log 2>&1 &
替换/path/to/your/script.sh和/path/to/output.log为实际值。保存并退出编辑器。
这将在系统启动时运行您的脚本。请注意,这种方法可能不如使用systemd服务稳定,因为cron服务可能在系统启动过程中的不同时间点运行。
建议使用systemd服务来实现更可靠的自动启动功能。