linux 开机自启 service
时间: 2023-09-25 21:16:07 浏览: 62
在Linux中,可以使用systemd或initd来管理服务的开机自启动。下面分别介绍这两种方法:
使用systemd开机自启:
1. 编写一个systemd服务文件。在/etc/systemd/system目录下新建一个.service文件,例如:
```
[Unit]
Description=My Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/my-service
Restart=always
[Install]
WantedBy=multi-user.target
```
其中,Description是服务的描述;After指定服务启动在网络之后;Type指定服务类型,simple表示直接执行ExecStart指定的命令;ExecStart指定服务启动时执行的命令;Restart指定服务异常退出后自动重启;WantedBy指定服务启动的运行级别。
2. 启动服务并设置开机自启。使用systemctl命令启动服务,并通过systemctl enable命令设置服务开机自启动,例如:
```
systemctl start my-service
systemctl enable my-service
```
使用initd开机自启:
1. 编写一个init脚本。在/etc/init.d目录下新建一个脚本文件,例如:
```
#!/bin/bash
#
# My Service
#
# chkconfig: 345 99 01
# description: My Service
case "$1" in
start)
/usr/bin/my-service
;;
stop)
killall my-service
;;
restart)
$0 stop
$0 start
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
esac
exit 0
```
其中,chkconfig指定服务启动的运行级别和启动顺序;start和stop分别指定服务启动和停止时执行的命令;restart指定重启时执行的命令。
2. 添加执行权限并设置开机自启。使用chmod命令添加执行权限,并使用chkconfig命令设置服务开机自启动,例如:
```
chmod +x /etc/init.d/my-service
chkconfig --add my-service
chkconfig my-service on
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)