ZBLOG

Go语言实现扫描/sys/bus/pci/devices/所有的PCI的vendor和device号

你可以使用Go语言中的osioutil包来读取文件并解析PCI设备信息。以下是一个示例代码:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

func main() {
	devicesPath := "/sys/bus/pci/devices/"

	files, err := ioutil.ReadDir(devicesPath)
	if err != nil {
		fmt.Println("无法读取PCI设备目录:", err)
		return
	}

	for _, file := range files {
		devicePath := filepath.Join(devicesPath, file.Name())

		vendorID, err := readDeviceAttribute(devicePath, "vendor")
		if err != nil {
			fmt.Println("无法读取Vendor ID:", err)
			continue
		}

		deviceID, err := readDeviceAttribute(devicePath, "device")
		if err != nil {
			fmt.Println("无法读取Device ID:", err)
			continue
		}

        fmt.Printf("设备: %s\nVendor ID: %s\nDevice ID: %s\n\n", file.Name(), vendorID, deviceID)
    }
}

func readDeviceAttribute(devicePath string, attributeName string) (string, error) {
	attrPath := filepath.Join(devicePath, attributeName)
	data, err := ioutil.ReadFile(attrPath)
	if err != nil {
	    return "", fmt.Errorf("无法读取属性 %s:%w", attributeName, err)
    }

	return strings.TrimSpace(string(data)), nil
}

这段代码会遍历/sys/bus/pci/devices/目录下的所有PCI设备,并获取每个设备的Vendor ID和Device ID。你可以根据需要进行进一步处理或输出。 请注意,此代码需要在拥有足够权限的系统上运行,以便访问/sys目录中的设备信息。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://sdn.0voice.com/?id=1761

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?