以用户身份运行 mac os x 应用程序不会自行停止

问题描述 投票:0回答:1

我正在创建 macOS 安装程序包。

为此,我使用安装后脚本文件来启动应用程序,然后加载 LaunchDaemon plist。

这是安装后脚本:

#!/bin/bash

cd /usr/local/TestApp
USER_NAME=$(who | head -1 | head -1 | awk '{print $1;}')
sudo -u $USER_NAME /usr/local/TestApp/Test.app/Contents/MacOS/Test -l

sudo launchctl load /Library/LaunchDaemons/com.testapp.plist

结果是它使用

sudo -u $USER_NAME /usr/local/TestApp/Test.app/Contents/MacOS/Test -l
命令启动应用程序,然后阻止,因为应用程序一直在运行。

因此,脚本会卡住,并且 LaunchDaemon 永远不会加载。

请告诉我以防万一我可以做什么。

bash macos launchd launch-daemon
1个回答
0
投票

如果您只想启动 Mac 应用程序 (

*.app
) 异步

  • open -a
    bundle 目录路径一起使用(以
    .app
    结尾)
  • 并在
    --args
    之后传递任何直通命令行参数(请参阅
    man open
    ):
sudo -u $USER_NAME open -a /usr/local/TestApp/Test.app --args -l

请参阅底部的注释,重新可靠地确定调用用户的用户名

$USER_NAME

如果由于某种原因,您确实需要直接定位

*.app
捆绑包中嵌入的可执行文件,则必须使用 Bash 的 &控制运算符在
后台
中运行命令: #!/bin/bash # Get the underlying username (see comments below). userName="${HOME##*/}" # Launch the app in the background, using control operator `&` # which prevents the command from blocking. # (Given that the installer runs the script as the root user, # `sudo` is only needed here for impersonation.) sudo -u "$userName" /usr/local/TestApp/Test.app/Contents/MacOS/Test -l & # Load the daemon. # (Given that the installer runs the script as the root user, # `sudo` is not needed here.) launchctl load /Library/LaunchDaemons/com.testapp.plist

请注意,我更改了确定基础用户名的方式:

  • ${HOME##*/}

    从底层用户的主目录路径

    $HOME
    中提取最后一个路径组件,该路径反映了调用安装程序的用户。
    
    

  • 这比使用不带参数的
  • who

    更强大,后者的输出可以包括

    other
    用户。

  • (顺便说一句,
who | head -1 | head -1 | awk '{print $1;}'

可以简化为更高效的

who | awk '{print $1; exit}
)。
    

© www.soinside.com 2019 - 2024. All rights reserved.