在golang中程序退出后如何保持子进程运行? [英] how to keep subprocess running after program exit in golang?

查看:112
本文介绍了在golang中程序退出后如何保持子进程运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到使用 Start()创建的子流程将在程序退出后终止,例如:

i noticed that subprocesses created using Start() will be terminated after program exit, for example:

package main

import "os/exec"

func main() {
    cmd := exec.Command("sh", "test.sh")
    cmd.Start()
}

main()退出时, test.sh 将停止运行

推荐答案

子进程应在进程结束后继续运行,只要它干净地结束即可,如果您按 ^ C 不会发生代码>.您可以做的是拦截发送到您的过程的信号,这样您就可以干净地结束了.

The subprocess should continue to run after your process ends, as long as it ends cleanly, which won't happen if you hit ^C. What you can do is intercept the signals sent to your process so you can end cleanly.

sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan,
    syscall.SIGINT,
    syscall.SIGKILL,
    syscall.SIGTERM,
    syscall.SIGQUIT)
go func() {
    s := <-sigchan
    // do anything you need to end program cleanly
}()

这篇关于在golang中程序退出后如何保持子进程运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆