macos - 当屏幕被锁定/关闭时,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")
解决方案
这似乎与屏幕锁定时 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)
}
}
}
}
推荐阅读
- javascript - 如何使用 Web 自定义协议打开 ElectronJS 应用程序?
- python - [Python]_ python 是否有像列表理解一样的字符串理解?
- mediawiki - 如何使用 Pywikibot 和 category.py 移动多个类别?
- c# - 我如何使用用户可能通过的任何比较器实现冒泡排序
- linux - Pine 脚本 - 如何编写检测八个相似连续蜡烛的脚本
- python - 我收到此错误 UnboundLocalError: local variable 'pay' referenced before assignment on line 9 每次请
- bash - 用于从日志文件中获取主机和每个主机的请求总数的 shell 脚本
- c++ - 搜索/过滤功能阻止主(GUI)线程
- php - 无法使用 Php 和 AJAX 检查复选框值
- shopify - 如何使用液体获得另一个选项(shopify)的第一个可用选项?