要在 Go 中获取所有进程,可以使用osos/exec 包中的函数。以下是一个示例代码:

package main

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
)

func main() {
	cmd := exec.Command("ps", "-e", "-o", "pid,ppid,comm")
	output, err := cmd.Output()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}

	processes := strings.Split(string(output), "\n")
	for _, process := range processes[1:] {
		fields := strings.Fields(process)
		if len(fields) >= 3 {
			pid := fields[0]
			ppid := fields[1]
			comm := fields[2]
			fmt.Printf("PID: %s, PPID: %s, Command: %s\n", pid, ppid, comm)
		}
	}
}

这个示例使用 ps 命令来获取所有进程的信息。-e 选项表示获取所有进程,-o 选项指定输出格式为 pid,ppid,comm,即进程 ID、父进程 ID 和命令名称。

然后,通过 exec.Command 函数创建一个命令对象,并调用 Output 方法执行命令。输出结果被读取并按行分割为字符串数组。

然后,遍历每个进程的信息并打印出进程 ID、父进程 ID 和命令名称。

请注意,此方法在不同的操作系统上可能会有所不同。在 Windows 上,可以使用 tasklist 命令来获取所有进程。在 Linux 上,可以使用 ps 命令或读取 /proc 目录中的进程信息文件。

Golang 获取所有进程:代码示例和跨平台解决方案

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

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