Search code examples
gogoland

keep external process running after exit


How do you keep a process running after main exit?

Update: It turns out it is only when you are running in goland. The accepted answer including comments solved this.

Info: I have an executable that watches a folder for changes, and I need to start it from go and keep it running after exit.

I have see this but it does not solve the problem of running the process after exit.

package main

import "os/exec"

func main() {
    cmd := exec.Command("sh", "long_running process", "&")
    cmd.Start()
}
fmt.Println("Sleeping...")
time.Sleep(8 * time.Second) // I can see the process running

Afterwards when I do "ps" the process is killed with the main application.


Solution

  • I can't recreate the issue you are having. When I run the sleep command and the goroutine terminates, it is still running when I search for it with ps

    Update

    1. Doesn't work running it with the debugger in GoLand.
    2. Except if you enable run as sudo in the debug options window.
    3. Without sudo: either with go run, or with dlv debug or without the debugger in GoLand.
    package main
    
    import (
        "os/exec"
    )
    
    func main() {
        cmd := exec.Command("sleep", "99999999")
        cmd.Start()
    }
    
    ~/tempgo/process
    ▶ go run process.go
    
    ~/tempgo/process
    ▶ ps -ax | grep "sleep"
    29907 ttys002    0:00.00 sleep 99999999
    29925 ttys002    0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn --exclude-dir=.idea --exclude-dir=.tox sleep
    
    ~/tempgo/process