macos - osx 安装脚本 - 检测 firefox 是否正在运行并提示重新启动

标签 macos bash firefox package productbuild

我正在为我的应用程序创建一个命令行工具。 它使用 pkgbuildproductbuild 来创建包。它是一个 launchdaemon 二进制文件。 我有 preinstallpostinstall 脚本。

安装后,可能在postinstall脚本中,我需要检测Firefox是否正在运行,然后提示用户需要重新启动Firefox。 可以这样做吗?如何?

脚本的一些摘录,它是安装后脚本的一部分。

.........

## Check if Firefox is running in the background with no tab/window open.


function restart_empty_firefox (){
    echo "Restarting firefox if no tab is opened. "

    firefoxRunning=$(osascript \
        -e 'tell application "System Events" to set fireFoxIsRunning to ((count of (name of every process where name is "Firefox")) > 0)' \
        -e 'if fireFoxIsRunning then' \
        -e 'set targetApp to "Firefox"' \
        -e 'tell application targetApp to count (every window whose (closeable is true))' \
        -e 'else' \
        -e 'return 0' \
        -e 'end if')

    if [ $firefoxRunning -eq 0 ]; then
        echo 'Firefox is in the background with no window and so quitting ...'
        osascript -e 'quit app "Firefox"'
    else 
        ##### show a dialog to the user to restart Firefox
    fi

}

firefox_update # not shown here
restart_empty_firefox

.............

最佳答案

您可以使用进程状态 (ps) 工具:

ps aux | grep '[F]irefox.app' | awk '/firefox$/ {print $2}'

结果:

82480

这告诉我们 Firefox.app 确实正在运行(进程 82480)。

编辑:由于您似乎倾向于使用osascript,这里有一个示例,要求用户重新启动 Firefox(将完全控制权交给他们) :

#!/bin/bash

osascript <<'END'
set theApp to "Firefox"
set theIcon to "Applications:Firefox.app:Contents:Resources:firefox.icns"

tell application "System Events"
    if exists process theApp then
        display dialog "Warning: Mozilla " & theApp & " should be closed." buttons {"Continue"} with icon file theIcon default button 1
        if the button returned of the result is "Continue" then
        end if
    end if
    display notification "Installation complete" with title "Application Package" subtitle "Please relaunch " & theApp
    delay 3
end tell
END

如果您的脚本有足够的权限,那么建议使用quit,而不是公然终止进程。最终应该这样做,否则只需要求用户退出并自行重新启动 Firefox — 问题就解决了。

关于macos - osx 安装脚本 - 检测 firefox 是否正在运行并提示重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32452779/

相关文章:

cocoa - 关于 NSoutlineView 和 WriteItem |拖放问题

bash - HandBrakeCLI 命令中断 while 循环?

linux - 有没有办法在 bash 脚本中的 awk 语句中定义用户定义的函数?

javascript - 如何解决不同浏览器上requestAnimationFrame中FPS不同的问题?

c++ - 不同的编译结果 : Mac vs Windows

c - 程序在mac os下运行正常,在linux下运行异常

javascript - DropzoneJS-索引大小错误: Index or size is negative or greater than the allowed amount

laravel - Firefox 强制开发域使用 SSL 和 Chrome

macos - 在菜单当前快速打开时从 NSTimer 动态更新 NSMenuItem?

bash - 使用 awk 将第二列移动到第一列