golang exec后台进程并得到它的pid

sbs*_*sbs 11 pid exec go

情况:

我想运行一个将自己置于后台的命令.如果它更有可能,那么我将在前台运行命令并将其自己带入后台.

题:

当进程在后台运行时:我怎样才能pid使用Go?

我尝试了以下方法:

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()
Run Code Online (Sandbox Code Playgroud)

这会立即返回并ssh在后台运行.但这pid不是pid正在运行的ssh过程.而且,它是pidssh进程之前的分叉和后台.

Rom*_*mov 15

你不需要任何特别的东西,只是不要告诉ssh背景本身而不是Wait()它.例:

$ 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
Run Code Online (Sandbox Code Playgroud)


小智 6

@Mostafa Hussein,可以使用goroutine等待,管理进程

function main()
    cmd := exec.Command( "shell.sh" )
    err := cmd.Start()
    if err != nil {
        return err
    }
    pid := cmd.Process.Pid
    // use goroutine waiting, manage process
    // this is important, otherwise the process becomes in S mode
    go func() { 
        err = cmd.Wait()
        fmt.Printf("Command finished with error: %v", err)
    }()
    return nil
}
Run Code Online (Sandbox Code Playgroud)