在 bash 上启动守护程序检查由 launchd 启动的脚本

Start daemon on bash check script started by launchd

关于 launchd 的快速问题,实际上是在 MacOS (Mojave) 上。 我正在使用 LLDP 守护程序(lldpd,可在此处获得 --> https://lldpd.github.io/

我想删除这个包创建的 plist (/Library/LaunchDaemons/im.bernat.lldpd.plist),并用我做的另一个替换它:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
     <key>Label</key>
     <string>XXX_LLDP_check</string>
     <key>UserName</key>
     <string>root</string>
     <key>ProgramArguments</key>
     <array>
          <string>/opt/xxx/lldp_check.sh</string>
     </array>
     <key>WatchPaths</key>
     <array>
           <string>/etc/resolv.conf</string>
           <string>/Library/Preferences/SystemConfiguration/NetworkInterfaces.plist</string>
     </array>
</dict>
</plist>

我在这里做的是观察 /etc/resolv.conf 和 /Library/Preferences/SystemConfiguration/NetworkInterfaces.plist 以便能够在网络接口状态发生变化时启动我的 /opt/xxx/lldp_check.sh 脚本。

然后此脚本将进行一些检查(DNS 解析、ping 等),以确保在启动 lldpd 守护程序之前我已连接到公司网络。

#!/bin/bash

sleep 5

ethernet_if=`networksetup -listallhardwareports | awk '/Ethernet/{getline;print}' | awk 'NR==1 {print }'`
ethernet_status=`ifconfig $ethernet_if | grep status | awk '{print }'`

if [ "$ethernet_status" = "active" ]
then
    echo "ETHERNET WIRED LINK IS UP" >> /tmp/test.log

    # some checks here (removed for sharing)
    if ping -c 1 1.1.1.1 &> /dev/null
    then
        echo "ON CORPORTATE NETWORK. STARTING LLDPD" >> /tmp/test.log
        /usr/local/sbin/lldpd &
        echo "LLDP started" >> /tmp/test.log
        # adding a sleep to see if it is started 
        sleep 10
    else
        echo "NOT ON CORPORATE NETWORK" >> /tmp/test.log
        killall lldpd
        echo "LLDP killed" >> /tmp/test.log
    fi
else
    echo "ETHERNET WIRED LINK DOWN" >> /tmp/test.log
    killall lldpd
    echo "LLDP killed" >> /tmp/test.log
fi

不幸的是,多亏了“sleep 10”,我能够看到 lldpd 启动了 10 秒,但随后在该检查脚本终止时被杀死。

我也尝试过使用“launchctl load /Library/LaunchDaemons/im.bernat.lldpd.plist”但没有成功。

我也尝试在“/usr/local/sbin/lldpd &”之前添加一个“nohup”,但它并没有使它变得更好。 如果我手动启动 /opt/xxx/lldp_check.sh(使用 root 权限),lldpd 会正确启动。

你有想法吗?

终于找到了解决方案:

  • 在bash 脚本
  • 中保持“拒绝”已启动的 lldpd 进程
  • 在 plist 文件 (AbandonProcessGroup) 中将“abandonprocessgroup”参数添加为“True”