当一个程序用命令行直接启动时,它和用户会话绑定,作为一个子进程child process。如果会话结束了,系统会发SIGTERM关闭给这个会话的所有子进程
Oct 21 19:15:42 ubuntu1 sshd[278675]: pam_unix(sshd:session): session closed for user niubile
Oct 21 19:15:42 ubuntu1 systemd-logind[784]: Session 52 logged out. Waiting for processes to exit.
Oct 21 19:15:42 ubuntu1 systemd[1]: session-52.scope: Deactivated successfully.
Oct 21 19:15:42 ubuntu1 systemd-logind[784]: Removed session 52.
Oct 21 19:15:52 ubuntu1 systemd[1]: Stopping User Manager for UID 1000...
Oct 21 19:15:52 ubuntu1 conmon[279742]: 1
Oct 21 19:15:52 ubuntu1 systemd[278678]: Stopping libcrun container...
Oct 21 19:15:52 ubuntu1 conmon[279742]: :signal-handler (
Oct 21 19:15:52 ubuntu1 conmon[279742]: 1697915752
Oct 21 19:15:52 ubuntu1 conmon[279742]: )
Oct 21 19:15:52 ubuntu1 conmon[279742]: Received SIGTERM scheduling shutdown...
要避免你的程序/服务被系统杀掉,可以写成systemd服务
vim /etc/systemd/system/myapp.service
注:myapp.service是个随意的名字,可以改
[Unit]
Description=My Java Application
[Service]
ExecStart=/usr/bin/java -jar /path/to/myapp.jar
User=myuser
Restart=always
RestartSec=3
LimitNOFILE=4096
[Install]
WantedBy=multi-user.target
RestartSec 和LimitNOFILE 表示 //重启前等待3秒 //这是最大文件开启数量
1. 启动 To start the service: sudo systemctl start myapp
2. 自启 To enable the service to start on boot: sudo systemctl enable myapp
3. 关闭 To stop the service: sudo systemctl stop myapp
4. 检查状态 To check the status of the service: sudo systemctl status myapp
其他避免被杀掉的方式:
- 启动时加
&
变成后台进程 java -jar yourapp.jar & - nohup 启动 nohup java -jar yourapp.jar &
- screen 或tmux 会话保持
其他进程被杀情景。爆内存OOM
可以在这里看内核日志: /var/log/kern.log
打脸了, & 并不能行,得tmux
主要原因是进程是用户会话的子进程,非root用户,回话结束时默认会关闭相关联的子进程。可以用loginctl enable-linger 用户名username