linuxgoconcurrencykonsole

Can you run an independent instance of a program from within Go?


I am looking for a way to launch a completely independent instance of a program from within a Go program. So far this is my best attempt:

  // Some code   

    go exec.Command("konsole", "--hold", "--separate", "sh", "-e", "go", "run", "test.go")
.Run()

    // Continue doing something else then quit

Using linux KDE's Konsole. This command "almost" works - it starts a new Konsole instance and runs the program. But they are dependent: if the first program is ended (ctrl+c), the second also ends. Is there a way to work around this problem?


Solution

  • In order to achieve it you need to replace exec.Command call with os.StartProcess giving extra process attributes os.ProcAttr and syscall.SysProcAttr. Setting flag Setpgid and leaving Pgid with default value of 0 achieves to goal as mentioned by @that_other_guy.

    package main
    
    import (
            "fmt"
            "os"
            "os/exec"
            "syscall"
    )
    
    func main() {
            cmd, err := exec.LookPath("sleep")
            if err != nil {
                    panic(err)
            }
            attr := &os.ProcAttr{
                    Sys: &syscall.SysProcAttr{
                            Setpgid: true,
                    },
            }
            process, err := os.StartProcess(cmd, []string{cmd, "1m"}, attr)
            if err != nil {
                    panic(err)
            }
            fmt.Println(process.Pid)
            process.Release()
            for {
            }
            return
    }