我有一个/etc/init.d/脚本,它在启动时启动并且需要联网。我将 rc start 设置为 99,所以它是最后加载的内容,但网络不会立即加载,我目前不得不依赖 30 秒的 sleep 命令来等待网络加载。
操作系统是为嵌入式系统(Yocto 项目)修改的 Ubuntu。文件系统相同,但服务非常有限,因此它使用 Sysvinit。
有没有办法检查所有网络是否已完成加载?
下面是脚本,如果有帮助的话:
#!/bin/sh
#
# Daemon Name: blerd
#
# chkconfig: - 3 99 1
# description: M3 Bluetooth Low Energy Relay Daemon
# Source function library.
. /etc/init.d/functions
PROGRAM=bler
LOCKFILE=/var/lock/subsys/$PROGRAM
start() {
[ -x $EXE ] || exit 5
echo -n "Starting $PROGRAM: ";
if [ -e $LOCKFILE ]; then
echo "Instance of $PROGRAM exists."
return 0;
fi
sleep 30
$PROGRAM
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
echo "Success"
else
echo "Failed"
fi
[ $RETVAL -eq 0 ] && touch $LOCKFILE
return $RETVAL
}
stop() {
echo -n "Stopping $PROGRAM: "
if [ ! -e $LOCKFILE ]; then
echo "No instance of $PROGRAM exists."
return 0;
fi
killproc $PROGRAM
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
echo "Success"
else
echo "Failed"
fi
[ $RETVAL -eq 0 ] && rm -f $LOCKFILE
return $RETVAL
}
status() {
echo -n "Status $PROGRAM: "
if [ -e $LOCKFILE ]; then
echo "Running"
else
echo "Stopped"
fi
return 0;
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
status
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
exit 2
;;
esac
最佳答案
基本的 Debian 方式:
基本上 /etc/network/if-up.d
是存放此类脚本的地方。当界面在 Debian 系统或衍生系统(如 Ubuntu)上启动时,将调用这些脚本。在这里您可以找到传递给这些脚本的环境变量列表。使用这些变量,您可以决定启动哪个接口(interface)以及接口(interface)配置的详细信息。在查看 /etc/network/if-up.d
示例脚本可能如下所示(源自 samba 包。只是为了解释它是如何工作的。如果您使用的是 Ubuntu,则应该使用 upstart
,稍后将进行解释)
/etc/network/if-up.d/your-service
#!/bin/sh
# Try to bring nmbd up when an interface comes up, if smbd is already running.
# Don't bother to do anything for lo.
if [ "$IFACE" = lo ]; then
exit 0
fi
# Only run from ifup.
if [ "$MODE" != start ]; then
exit 0
fi
# we only care about inet and inet6.
case $ADDRFAM in
inet|inet6|NetworkManager)
;;
*)
exit 0
;;
esac
# start the service
invoke-rc.d your-service start >/dev/null
exit 0
注意您需要
chmod +x /etc/network/if-up.d/your-service
Ubuntu/Upstart:
Ubuntu 正在使用 upstart
作为 sysvinit 的替代品。如果您正在查看 /etc/network/if-up.d/
,您会看到 upstart
也在那里放置了一个钩子(Hook)。这个钩子(Hook)是更详细的 upstart
机制的基础,它提供了启动服务的可能性,除非已经启动了某个网络接口(interface)。 upstart 钩子(Hook)将触发事件 net-device-up
并传递 IFACE
、LOGICAL
、ADDRFAM
和 METHOD
作为参数。您在 upstart 脚本中为您的服务使用此 Hook (如提到的@Guy):
start on net-device-up IFACE=eth0
关于bash - 如何在/etc/init.d 脚本中检测网络何时初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20478516/