脚本放在 /usr/local/etc/rc.d/
目录下,需要 chmod +x
赋予运行权限,还需要在/etc/rc.conf
启用
1.程序有自带daemon进程
chmod +x /usr/local/etc/rc.d/kas
#!/bin/sh
. /etc/rc.subr
name=qbittorrent
rcvar=qbittorrent_enable
qbittorrent_flags="--daemon"
command="/usr/local/bin/qbittorrent-nox"
load_rc_config $name
run_rc_command "$1
chmod +x /usr/local/etc/rc.d/qbittorrent
sysrc qbittorrent_enable="YES"
注意点:
qbittorrent_flags
是参数
command
是启动程序的命令,不能带参数,不能空格
通常此类服务可以直接替换示例中所有的qbittorrent
和调整flags
参数来实现开机启动和服务管理
2.直接运行在前台在屏幕上打印一堆log的
来源:https://gist.github.com/apearson/56a2cd137099dbeaf6683ef99aa43ce0
这种需要调用系统的daemon来运行守护进程(吐槽一下这比systemd麻烦多了,FreeBSD应该去想办法去构建一个更现代化的rc)
这里以一个名为kas
的程序示例,该程序运行在www
用户下
nano /usr/local/etc/rc.d/kas
#!/bin/sh
#
# PROVIDE: kas
# REQUIRE: LOGIN
# KEYWORD: shutdown
# Author: Andrew Pearson (apearson.io)
# Version: 1.0.2
# Description:
# This script runs kas as a service under the supplied user on boot
# How to use:
# Place this file in /usr/local/etc/rc.d/
# Add kas_enable="YES" to /etc/rc.config
# (Optional) To run as non-root, add kas_runAs="your_user_name" to /etc/rc.config
# (Optional) To pass kas args, add kas_args="" to /etc/rc.config
# Freebsd rc library
. /etc/rc.subr
# General Info
name="kas" # Safe name of program
program_name="kas" # Name of exec
title="kas" # Title to display in top/htop
# RC.config vars
load_rc_config $name # Loading rc config vars
: ${kas_enable="NO"} # Default: Do not enable kas
: ${kas_runAs="www"} # Default: Run kas as root
# Freebsd Setup
rcvar=kas_enable # Enables the rc.conf YES/NO flag
pidfile="/var/run/${program_name}.pid" # File that allows the system to keep track of kas status
# Env Setup
export HOME=$( getent passwd "$kas_runAs" | cut -d: -f6 ) # Gets the home directory of the runAs user
# Command Setup
exec_path="/usr/local/bin/${program_name}" # Path to the kas exec, /usr/local/bin/ when installed globally
output_file="/var/log/${program_name}.log" # Path to kas output file
# Command
command="/usr/sbin/daemon"
command_args="-r -t ${title} -u ${kas_runAs} -o ${output_file} -P ${pidfile} ${exec_path} ${kas_args}"
# Loading Config
load_rc_config ${name}
run_rc_command "$1"
编辑/etc/rc.config
(root用户运行此步可省略)
nano /etc/rc.config
写入
kas_runAs="www"
chmod +x /usr/local/etc/rc.d/kas
sysrc kas_enable="YES"
这里把所有的kas
换成你的程序名,用户换成指定用户即可
注意点:
两个文件里的 kas_runAs="www"
是运行在指定用户下必要的字段。root用户运行把www
改成root
,不需要编辑/etc/rc.config
exec_path="/usr/local/bin/${program_name}"
可以直接写绝对路径指定,例如/var/www/kas
可以用kas_args=""
在/etc/rc.config
里面指定参数
总结
以上两种类型基本够用。
最后一条提醒:在nano里使用ctrl + \
可以批量替换文本
Systemd大法好!