简体   繁体   中英

How do I list block devices in Go?

I want to get the data shown by lsblk command in Linux 64-bit systems. Obviously I can call lsblk and parse the output. My question is if there is a better way to do this in Go?

Thanks.

Since lsblk is already available and already does what you want (gathering information from the system and synthesizing that information into the form you want), I'd think using it would be the best way.

The lsblk source code is here: https://github.com/karelzak/util-linux/blob/master/misc-utils/lsblk.c . At first glance, personally, this seems nontrivial to replicate in Go, and probably worth the hassle of parsing output and testing for breakage when the util-linux package is updated.

That's ultimately a decision that has to be made for your individual project based on your particular criteria.

I just needed the names of the top-level devices and ended up simply listing the contents of /sys/block , which was convenient because it requires neither running a command, nor parsing output.

func GetDevices() []string {
    dir, err := ioutil.ReadDir("/sys/block")
    if err != nil {
        panic(err)
    }

    files := make([]string, 0)

    for _, f := range dir {
        if strings.HasPrefix(f.Name(), "loop") {
            continue
        }
        files = append(files, f.Name())
    }

    return files
}

Neither a very robust or portable solution, but worked for what I needed.

You could also conceive parsing the contents of /proc/diskstats or /proc/partitions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM