使用 Golang 从子进程 ID 获取父进程 ID

kms*_*kms 6 linux go

我想使用 Golang for Linux os 从特定子进程 id (pid) 获取父进程 id (ppid)

我有这段代码,它提供当前进程的 ppid 和 pid,但我想检索我指定的子进程的 ppid,而不是当前进程。

package main

 import (
         "fmt"
         "os"
 )

 func main() {

         pid := os.Getpid()

         parentpid := os.Getppid()

         fmt.Printf("The parent process id of %v is %v\n", pid, parentpid)

 }
Run Code Online (Sandbox Code Playgroud)

有没有办法像这样传递 pidos.Getppid(pid)或任何其他方法来检索 Golang 中指定 pid 的 ppid ?

bit*_*voc 4

我认为 go 标准库不允许您执行此操作,但是, mitchellh/go-ps等第三方软件包提供了更多信息。

例子:

import ps "github.com/mitchellh/go-ps"
...

list, err := ps.Processes()
if err != nil {
  panic(err)
}
for _, p := range list {
  log.Printf("Process %s with PID %d and PPID %d", p.Executable(), p.Pid(), p.PPid())
}
Run Code Online (Sandbox Code Playgroud)

输出:

2019/06/12 09:13:04 Process com.apple.photom with PID 68663 and PPID 1
2019/06/12 09:13:04 Process CompileDaemon with PID 49896 and PPID 49895
Run Code Online (Sandbox Code Playgroud)

您还可以用来ps.FindProcess(<pid>)查找特定进程并检查其 PPid