gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:08:36 27 4
gpt4 key购买 nike

我想使用适用于 Linux 操作系统的 Golang 从特定子进程 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)

}

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

最佳答案

我不认为 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())
}

输出:

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

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

关于linux - 使用 Golang 从子进程 ID 获取父进程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56563992/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com