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

时间:2016-09-15 09:53:01

标签: go exec pid

情况:

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

问题:

当流程在后台运行时:如何使用Go获取pid

我尝试了以下内容:

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不是正在运行的pid进程的ssh。此外,它是父pid进程的ssh,然后才进行分叉和自我支持。

2 个答案:

答案 0 :(得分:14)

你不需要任何特别的东西,只是不要告诉ssh背景本身而不是$ 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 。例如:

public class MyActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

答案 1 :(得分:1)

@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
}