我想运行一个将自己置于后台的命令(或者如果它使事情变得更有可能,在前台模式下运行命令并自己运行它),并获得后台进程的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()
这会立即返回〜,让ssh在后台运行,但是pid不是正在运行的ssh进程的pid(可能是它在分叉和后台自身之前的父ssh进程的pid).
我该怎么做呢?
你不需要任何特殊的东西,只是不要告诉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