【问题标题】:cannot get real hostname when launching shell script at boot with launchd使用 launchd 在启动时启动 shell 脚本时无法获取真实主机名
【发布时间】:2013-04-23 16:23:21
【问题描述】:

我正在尝试通过 /Library/LaunchDaemons 中的 plist 文件(在 10.8.x 上,如果重要的话)使用 launchd 在启动时运行 shell 脚本:

<?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>testD</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/lfriedman/cuda-stuff/sw/gpgpu/build/scripts/testing/testD.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
        <true/>
    <key>UserName</key>
    <string>lfriedman</string>
    <key>AbandonProcessGroup</key>
    <false/>
    <key>StandardOutPath</key>
    <string>/tmp/testD.out</string>
    <key>StandardErrorPath</key>
    <string>/tmp/testD.err</string>
</dict>
</plist>

在 shell 脚本中调用了“hostname -s”。如果我手动运行脚本,一切正常。如果我通过 cron 运行脚本,一切正常。但是,当它通过 launchd 在引导时运行时,从“hostname -s”返回的值总是(错误地)返回为“localhost”,而不是系统的实际主机名。如果我调整 plist 以在启动时以外的时间运行脚本,它也会做正确的事情并返回系统的实际短主机名。这让我想到,在操作系统的网络子系统完全运行之前,launchd 正在启动它的工作,这会导致某种竞争条件。

是否有一些特殊的方法可以确保操作系统在 launchd 运行作业之前“完全”启动?或者在调用程序之前在 plist 文件中强制延迟的方法?

【问题讨论】:

    标签: macos plist launchd


    【解决方案1】:

    不幸的是,launchd 无法设置依赖项,因此您需要在脚本中设置延迟。在 shell 脚本中,检查网络的简单方法是:

    #!/bin/bash
    
    # Example Daemon Starter
    . /etc/rc.common
    
    CheckForNetwork
    
    while [ "${NETWORKUP}" != "-YES-" ]
    do
        sleep 5
        NETWORKUP=
        CheckForNetwork
    done
    
    # Now do what you need to do.
    

    您可以在以下链接中查看更多信息: http://blog.slaunchaman.com/2010/07/01/how-to-run-a-launchdaemon-that-requires-networking/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多