douyongdao4046 2016-09-15 09:53
浏览 1229
已采纳

golang exec后台进程并获取其pid

Situation:

I want to run a command that puts itself into the background. If it makes it more possible, then I'll run the command in foreground and bring it into the background by myself.

Question:

When the process runs in background: how can I get it's pid using Go?

I tried the following:

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 and leaves ssh running in the background. But it's pid is not the pid of the running ssh process. Moreover, it's the pid of the parent ssh process before it forked and backgrounded itself.

  • 写回答

2条回答 默认 最新

  • douhao7677 2016-09-15 14:02
    关注

    You don't need anything special, just don't tell ssh to background itself 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
    ", 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决