要在 Golang 中获取进程,可以使用 'os' 包中的 'FindProcess' 函数。这个函数需要传入进程的 ID(PID)作为参数,并返回一个 '*os.Process' 类型的对象,代表该进程。

下面是一个示例代码,演示如何获取当前进程的信息:

package main

import (
	"fmt"
	"os"
)

func main() {
	pid := os.Getpid() // 获取当前进程的 ID
	process, err := os.FindProcess(pid)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Process ID:", process.Pid)
	fmt.Println("Parent Process ID:", process.PPid())
	fmt.Println("Process ID of the calling process:", os.Getppid())
}

运行以上代码,将输出当前进程的 ID、父进程的 ID 以及调用该程序的进程的 ID。

注意:'FindProcess' 函数返回的 '*os.Process' 对象只是一个表示进程的句柄,并不能直接获取进程的详细信息。如果需要获取更多关于进程的信息,可以使用 'Process' 结构体提供的其他方法,例如 'Process.Signal' 发送信号给进程,'Process.Wait' 等待进程结束等。

Golang 获取进程:详解 FindProcess 函数和进程信息获取

原文地址: https://www.cveoy.top/t/topic/qrl0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录