Golang execute background process and get its pid

I want to run a command that is placed in the background (or, if this makes things more possible, run the command in the foreground and remember it yourself) and get the pid of the background process. How to do it in Go? I tried:

cmd := exec.Command("ssh", "-i", keyFile, "-o", "ExitOnForwardFailure yes", "-fqnNTL", fmt.Sprintf("%d:127.0.0.1:%d", port, port), fmt.Sprintf("% s@ %s", serverUser, serverIP)) cmd.Start() pid := cmd.Process.Pid cmd.Wait() 

This returns ~ instantly, leaves ssh in the background, but the pid is not the pid of the current ssh process (presumably this is the pid of the ssh parent process before it branches and comment out itself).

How to do it right?

+5
source share
1 answer

You don't need anything, just don't say ssh in the background and don't Wait() for it. Example:

 $ cat script.sh #!/bin/sh sleep 1 echo "I'm the script with pid $$" for i in 1 2 3; do sleep 1 echo "Still running $$" done $ cat proc.go package main import ( "log" "os" "os/exec" ) func main() { cmd := exec.Command("./script.sh") cmd.Stdout = os.Stdout err := cmd.Start() if err != nil { log.Fatal(err) } log.Printf("Just ran subprocess %d, exiting\n", cmd.Process.Pid) } $ go run proc.go 2016/09/15 17:01:03 Just ran subprocess 3794, exiting $ I'm the script with pid 3794 Still running 3794 Still running 3794 Still running 3794 
+10
source

All Articles