Fedora设置rc.local/rc-local.service系统启动时自动执行脚本命令

文章
Fedora设置rc.local/rc-local.service系统启动时自动执行脚本命令-下一朵云

系统为fedora 26,想在系统启动时自动执行frpc的脚本文件,Centos7系统下将命令添加至/etc/rc.d/rc.local文件内即可,但是fedora系统遇到如下问题:

1.系统默认没有rc.local文件

2.启动rc-local.service报错

3.rc.local内的命令行不执行,手动重启rc-local.service又会被执行

解决办法:

1.1 创建rc.local文件

vi /etc/rc.d/rc.local

1.2 复制如下内容

#!/bin/bash

touch /var/lock/subsys/local
#此行保证rc.lcoal内命令行不被重复执行
#/var/lock/subsys/local这个文件的存在证明rc.local这个脚本已经执行过了

setsid /usr/local/frp/frpc --clientid=188888888 >/dev/null 2>&1 &
#此行为本人想随系统启动执行的命令

1.3 保存并添加执行权限给rc.local

:wq
chmod +x rc.local

2.1 设置开机启动rc-local.service服务

systemctl enable rc-local.service

此时如果出现如下报错:

[root@fedora system]# systemctl enable rc-local.service
The unit files have no installation config (WantedBy, RequiredBy, Also, Alias
settings in the [Install] section, and DefaultInstance for template units).
This means they are not meant to be enabled using systemctl.
Possible reasons for having this kind of units are:
1) A unit may be statically enabled by being symlinked from another unit's
   .wants/ or .requires/ directory.
2) A unit's purpose may be to act as a helper for some other unit which has

说明rc-local.service中缺少[Install]字段

2.2 修改 rc-local.service

vim /usr/lib/systemd/system/rc-local.service

添加如下内容:

[Install]
WantedBy=multi-user.target
Fedora设置rc.local/rc-local.service系统启动时自动执行脚本命令-下一朵云

2.3 重新设置rc-local.service服务开机自启

systemctl enable rc-local.service

此时,无任何报错提示,重启系统

Fedora设置rc.local/rc-local.service系统启动时自动执行脚本命令-下一朵云

3.1 重启系统后发现frpc并未启动,即rc.lcoal中的命令并未执行

Fedora设置rc.local/rc-local.service系统启动时自动执行脚本命令-下一朵云

其原因在于systemd的并行启动机制,导致rc.local执行时间太早,在系统还没有完全初始化(例如网络功能等)就已经执行了此脚本,导致脚本中的命令失败。

解决的方法很简单,修改/usr/lib/systemd/system/rc-local.service, 添加依赖服务(syslog、network-online):

#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.d/rc.local is executable.
[Unit]
Description=/etc/rc.d/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.d/rc.local
After=syslog.target network.target network-online.target
#此行为修改内容,添加 syslog network-online

[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no

# Add-Install 2020-07-22
[Install]
WantedBy=multi-user.target
Fedora设置rc.local/rc-local.service系统启动时自动执行脚本命令-下一朵云

3.2 保存后重启系统,发现rc.local内的命令已被正常执行

Fedora设置rc.local/rc-local.service系统启动时自动执行脚本命令-下一朵云

至此,我们找回了常用的rc.local功能!