duanliang2017
2017-02-26 16:50
浏览 832
已采纳

在golang中程序退出后如何保持子进程运行?

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()
}

when main() exits, test.sh will stop running

图片转代码服务由CSDN问答提供 功能建议

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

 包main 
 
import“ os / exec” 
 
func main(){
 cmd:= exec.Command(“ sh”,  “ test.sh”)
 cmd.Start()
} 
   
 
 

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dqotv26286 2017-02-26 17:21
    已采纳

    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
    }()
    
    打赏 评论
  • douceng7070 2017-02-26 16:59

    Try modding you program a to use Run instead of start. In that way the Go program will wait for the sh script to finish before exiting.

    package main
    
    import (
        "log"
        "os/exec"
    )
    
    func main() {
        cmd := exec.Command("sh", "test.sh")
        err := cmd.Run()
        if err != nil {
            log.Fatalln(err)
        }
    }
    

    Likewise, you could always use a wait group but I think that's overkill here.

    You could also just a go routine with or without a wait group. Depends on if you want go to wait for the program the sh program to complete

    package main
    
    import (
        "os/exec"
    )
    
    func runOffMainProgram() {
        cmd := exec.Command("sh", "test.sh")
        cmd.Start()
    }
    
    func main() {
        // This will start a go routine, but without a waitgroup this program will exit as soon as it runs
        // regardless the sh program will be running in the background. Until the sh program completes
        go runOffMainProgram()
    }
    
    打赏 评论

相关推荐 更多相似问题