Skip to content

freebsd由于没使用systemd,所以会采用配置/etc/rc.d/文件的方式配置服务启动

服务模拟脚本

开机自启动脚本执行的时候不能阻塞,freebsd服务启动的时候是串行执行的,一条命令卡住,所有后续服务不能执行

新建脚本/root/test-boot.sh,注意最后面要加上&以免阻塞

sh
#!/bin/sh
sh -c "while true;do date >> /root/test-boot.log; sleep 1; done" &
#!/bin/sh
sh -c "while true;do date >> /root/test-boot.log; sleep 1; done" &

下面执行脚本

shell
$ chmod a+x test-boot.sh
$ ./test-boot.sh
$ chmod a+x test-boot.sh
$ ./test-boot.sh

检查效果

shell
$ tail -f /root/test-boot.log
$ tail -f /root/test-boot.log

配置开机启动

如下配置是照抄freebsd官方文档Starting Services

主要的不同是把原文中的配置文件从utility参数全部替换为test_boot,即utility服务替换为test_boot服务,该服务会在DAEMON pseudo-service之后启动

注意不要携带后缀.sh

/etc/rc.d/test_boot

sh
#!/bin/sh
# 
# PROVIDE: test_boot
# REQUIRE: DAEMON
# KEYWORD: shutdown

. /etc/rc.subr
name=test_boot
rcvar=test_boot_enable
command="/root/test-boot.sh"

load_rc_config $name

#
# DO NOT CHANGE THESE DEFAULT VALUES HERE
# SET THEM IN THE /etc/rc.conf FILE
#
test_boot_enable=${test_boot_enable-"NO"}
pidfile=${test_boot_pidfile-"/var/run/test_boot.pid"}

run_rc_command "$1"
#!/bin/sh
# 
# PROVIDE: test_boot
# REQUIRE: DAEMON
# KEYWORD: shutdown

. /etc/rc.subr
name=test_boot
rcvar=test_boot_enable
command="/root/test-boot.sh"

load_rc_config $name

#
# DO NOT CHANGE THESE DEFAULT VALUES HERE
# SET THEM IN THE /etc/rc.conf FILE
#
test_boot_enable=${test_boot_enable-"NO"}
pidfile=${test_boot_pidfile-"/var/run/test_boot.pid"}

run_rc_command "$1"

参数与命令解释

  • . /etc/rc.subr: 加载rc.subr定义的参数和函数

  • PROVIDE: test_boot: 指定此文件所提供的服务的名字,该字段是必须的

  • REQUIRE: DAEMON: 列出此服务启动之前所需要的其他服务,非必须字段,但是推荐自定义的服务填写为DAEMON,这样可以保证自定义服务在所有通用守护进程之后运行,以免太早运行产生不必要的依赖错误

  • name=test_boot: 配置服务名称是test_boot

  • rcvar=test_boot_enable: 配置服务是否开机自启动参数, 可以使用/etc/rc.d/test_boot rcvar命令来检查服务是否在/etc/rc.conf中被启用

  • command="/root/test-boot.sh": 配置启动命令位置, 如果该服务是阻塞的,则需要修改command="some-service &"

更多配置项或者使用可以参考/etc/rc.d/sshd文件

增加执行权限

shell
$ chmod a+x /etc/rc.d/test_boot
$ chmod a+x /etc/rc.d/test_boot

编辑/etc/rc.conf,新增一行数据允许开机自启动

sh
test_boot_enable="YES"
test_boot_enable="YES"

最后重启查看/root/test-boot.log文件验证

拓展阅读

配置freebsd软件包源为国内中科大源

创建配置文件/usr/local/etc/pkg/repos/FreeBSD.conf

ini
FreeBSD: {
  url: "pkg+http://mirrors.ustc.edu.cn/freebsd-pkg/${ABI}/quarterly",
}
FreeBSD: {
  url: "pkg+http://mirrors.ustc.edu.cn/freebsd-pkg/${ABI}/quarterly",
}

更新索引

shell
$ pkg update -f
$ pkg update -f

安装vim

shell
$ pkg install vim
$ pkg install vim

参考阅读

freebsd官方文档Starting Services

FreeBSD System Manager's Manual

中科大FreeBSD pkg 源使用帮助

Last updated:

Released under the MIT License.