首页 > 解决方案 > 当屏幕被锁定/关闭时,cmd.Run() 在 Macos 上的 golang 中永远挂起

问题描述

我在 Macos 上运行一个 golang 应用程序。它有一些代码,如下所示:

for {
    time.Sleep(time.Second * 5)
    cmd := exec.Command("/usr/bin/osascript", "-e", `display dialog "hello" with title "hello"`)
    err := cmd.Run()
}

如果我不锁定屏幕(当屏幕始终打开时),它工作正常。但是err := cmd.Run()如果在该行执行时屏幕被锁定并关闭,代码将永远挂起。当我解锁屏幕(打开它)时,for循环永远挂在那里,永远不会继续执行。

我不确定这个问题是否属于 golang 或 MacOS 如何处理 osascript。谁能告诉我如何解决它?非常感谢。

PS:我在 Linux 中使用相同的代码并替换/usr/bin/osascript/usr/bin/xmessage,即使在 Linux 中屏幕被锁定/关闭,它也总是可以正常工作而没有任何问题。

编辑:

我的解决方案,改用 chrome:

cmd := exec.Command(`/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`, "-new-window", "/path/hello.html")

标签: macosgoosascript

解决方案


这似乎与屏幕锁定时 MacOS 如何使进程处于空闲状态有关。它使osasscript子进程永远不会完成执行并阻塞for循环。

您可以做的一件事是使用超时上下文运行命令。我已经尝试过了,它有效。当屏幕解锁并且超时到期时,将恢复执行。

例子:

package main

import (
    "context"
    "fmt"
    "os/exec"
    "time"
)

func main() {
    for {
        time.Sleep(time.Second * 5)

        // run your command with a timeout
        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        cmd := exec.CommandContext(
            ctx,
            "/usr/bin/osascript",
            "-e",
            `display dialog "hello" with title "hello"`,
        )

        err := cmd.Run()
        if err != nil {
            fmt.Println(err)
        }
        // don't forget to cancel your context to avoid context leak
        cancel()
    }
}

或者,如果您不希望超时,您可以在尝试调用显示对话框之前检查屏幕是否已锁定。

package main

import (
    "context"
    "fmt"
    "os"
    "os/exec"
    "strings"
    "time"
)

func main() {
    for {
        time.Sleep(time.Second * 5)

        ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
        cmd := exec.CommandContext(
            ctx,
            "python",
            "-c",
            "import sys,Quartz; d=Quartz.CGSessionCopyCurrentDictionary(); print d",
        )

        var err error
        var b []byte
        if b, err = cmd.CombinedOutput(); err != nil {
            cancel()
            continue
        }
        cancel()

        // if screen is not locked
        if !strings.Contains(string(b), "CGSSessionScreenIsLocked = 1") {
            cmd = exec.Command(
                "/usr/bin/osascript",
                "-e",
                "display dialog \"Hello\"",
            )
            cmd.Stdout = os.Stdout
            cmd.Stderr = os.Stderr

            err = cmd.Run()
            if err != nil {
                fmt.Println("err: ", err)
            }
        }
    }
}

推荐阅读