os.Wait() 不等待 golang 中的程序终止
os.Wait() does not wait for program termination in golang
在我的代码执行过程中的某个时刻,我希望我的程序启动一个编辑器(无论是哪个编辑器)供用户执行一些实时编辑。
我需要我的程序在此时停止,直到用户决定关闭编辑器(或多或少 git rebase 的工作方式)
我是这样处理的
func main() {
fpath := os.TempDir() + "/afile.txt"
f, err := os.Create(fpath)
if err != nil {
log.Fatal(err)
}
defer f.Close()
cmd := exec.Command("/usr/local/bin/code", fpath)
err = cmd.Start()
if err != nil {
log.Fatal(err)
}
err = cmd.Wait()
if err != nil {
fmt.Println(err)
}
}
没有错误被打印出来,但是上面的代码,虽然它当然会打开 vscode
,但它会在用户关闭编辑器之前终止 (returns)。
cmd.Wait()
不应该处理这个吗?
程序在 MacOS Catalina fwiw 上执行。
Shouldn't cmd.Wait() be handling this?
是的,确实如此。 Go 按预期等待,这是您对 /usr/local/bin/code
的调用不正确,不会等待。 code
的默认行为是在生成 VSCode window 后立即退出。它不会等待 window 关闭,因此 Go 不能等待 window 关闭。
尝试在您的终端中输入 code
。你会发现它立即退出,即使你的 VSCode window 仍然打开。
要使 code
阻塞直到编辑器 window 关闭(从而允许 Go 等待),您需要将 -w
或 --wait
标志传递给它.再次尝试在您的终端中使用 code -w
。在 VSCode window 关闭之前,您会找到终端命令块。
实际上,你只需要改变这个...
cmd := exec.Command("/usr/local/bin/code", fpath)
对此:
cmd := exec.Command("/usr/local/bin/code", "-w", fpath)
// or
// cmd := exec.Command("/usr/local/bin/code", "--wait", fpath)
根据https://golang.org/pkg/os/exec/#Cmd.Start
Start starts the specified command but does not wait for it to
complete.
If Start returns successfully, the c.Process field will be set.
The Wait method will return the exit code and release associated
resources once the command exits.
如果可以 strace code
,您会在底部 linux 中找到 +++ exited with 0 +++
。
基本上,启动 vscode 的命令会退出,clones
(一种分支)因此不会等待 return。
strace code -w
实际上等待 vscode 退出。
在我的代码执行过程中的某个时刻,我希望我的程序启动一个编辑器(无论是哪个编辑器)供用户执行一些实时编辑。
我需要我的程序在此时停止,直到用户决定关闭编辑器(或多或少 git rebase 的工作方式)
我是这样处理的
func main() {
fpath := os.TempDir() + "/afile.txt"
f, err := os.Create(fpath)
if err != nil {
log.Fatal(err)
}
defer f.Close()
cmd := exec.Command("/usr/local/bin/code", fpath)
err = cmd.Start()
if err != nil {
log.Fatal(err)
}
err = cmd.Wait()
if err != nil {
fmt.Println(err)
}
}
没有错误被打印出来,但是上面的代码,虽然它当然会打开 vscode
,但它会在用户关闭编辑器之前终止 (returns)。
cmd.Wait()
不应该处理这个吗?
程序在 MacOS Catalina fwiw 上执行。
Shouldn't cmd.Wait() be handling this?
是的,确实如此。 Go 按预期等待,这是您对 /usr/local/bin/code
的调用不正确,不会等待。 code
的默认行为是在生成 VSCode window 后立即退出。它不会等待 window 关闭,因此 Go 不能等待 window 关闭。
尝试在您的终端中输入 code
。你会发现它立即退出,即使你的 VSCode window 仍然打开。
要使 code
阻塞直到编辑器 window 关闭(从而允许 Go 等待),您需要将 -w
或 --wait
标志传递给它.再次尝试在您的终端中使用 code -w
。在 VSCode window 关闭之前,您会找到终端命令块。
实际上,你只需要改变这个...
cmd := exec.Command("/usr/local/bin/code", fpath)
对此:
cmd := exec.Command("/usr/local/bin/code", "-w", fpath)
// or
// cmd := exec.Command("/usr/local/bin/code", "--wait", fpath)
根据https://golang.org/pkg/os/exec/#Cmd.Start
Start starts the specified command but does not wait for it to complete.
If Start returns successfully, the c.Process field will be set.
The Wait method will return the exit code and release associated resources once the command exits.
如果可以 strace code
,您会在底部 linux 中找到 +++ exited with 0 +++
。
基本上,启动 vscode 的命令会退出,clones
(一种分支)因此不会等待 return。
strace code -w
实际上等待 vscode 退出。