在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

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

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