在Golang中获取系统的磁盘空间内存占用

获取磁盘占用情况(Linux/Mac下有效)

import (
    "syscall"
)

type DiskStatus struct {
    All  uint64 `json:"all"`
    Used uint64 `json:"used"`
    Free uint64 `json:"free"`
}

// disk usage of path/disk
func DiskUsage(path string) (disk DiskStatus) {
    fs := syscall.Statfs_t{}
    err := syscall.Statfs(path, &fs)
    if err != nil {
        return
    }
    disk.All = fs.Blocks * uint64(fs.Bsize)
    disk.Free = fs.Bfree * uint64(fs.Bsize)
    disk.Used = disk.All - disk.Free
    return
}

获取内存占用

import (
    "runtime"
)

type MemStatus struct {
    All  uint32 `json:"all"`
    Used uint32 `json:"used"`
    Free uint32 `json:"free"`
    Self uint64 `json:"self"`
}

func MemStat() MemStatus {
    //自身占用
    memStat := new(runtime.MemStats)
    runtime.ReadMemStats(memStat)
    mem := MemStatus{}
    mem.Self = memStat.Alloc

    //系统占用,仅linux/mac下有效
    //system memory usage
    sysInfo := new(syscall.Sysinfo_t)
    err := syscall.Sysinfo(sysInfo)
    if err == nil {
        mem.All = sysInfo.Totalram * uint32(syscall.Getpagesize())
        mem.Free = sysInfo.Freeram * uint32(syscall.Getpagesize())
        mem.Used = mem.All - mem.Free
    }
    return mem
}

后记

  1. 很明显,Windows下的支持是最弱的, 当然,还能通过调用win32 API的方式获取缺失的信息
  2. Golang的API并非完全跨平台, 正如上述的syscall.Statfs_t结构体,在Windows下是没有的

2013年4月6号更新,windows下获取磁盘空间的方法

通过调用win32 api

func main() {
    kernel32, err := syscall.LoadLibrary("Kernel32.dll")
    if err != nil {
        log.Panic(err)
    }
    defer syscall.FreeLibrary(kernel32)
    GetDiskFreeSpaceEx, err := syscall.GetProcAddress(syscall.Handle(kernel32), "GetDiskFreeSpaceExW")

    if err != nil {
        log.Panic(err)
    }

    lpFreeBytesAvailable := int64(0)
    lpTotalNumberOfBytes := int64(0)
    lpTotalNumberOfFreeBytes := int64(0)
    r, a, b := syscall.Syscall6(uintptr(GetDiskFreeSpaceEx), 4,
        uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("C:"))),
        uintptr(unsafe.Pointer(&lpFreeBytesAvailable)),
        uintptr(unsafe.Pointer(&lpTotalNumberOfBytes)),
        uintptr(unsafe.Pointer(&lpTotalNumberOfFreeBytes)), 0, 0)

    log.Printf("Available  %dmb", lpFreeBytesAvailable/1024/1024.0)
    log.Printf("Total      %dmb", lpTotalNumberOfBytes/1024/1024.0)
    log.Printf("Free       %dmb", lpTotalNumberOfFreeBytes/1024/1024.0)
}

或者更简单的版本

func main() {
    h := syscall.MustLoadDLL("kernel32.dll")
    c := h.MustFindProc("GetDiskFreeSpaceExW")
    lpFreeBytesAvailable := int64(0)
    lpTotalNumberOfBytes := int64(0)
    lpTotalNumberOfFreeBytes := int64(0)
    r2, _, err := c.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("F:"))),
        uintptr(unsafe.Pointer(&lpFreeBytesAvailable)),
        uintptr(unsafe.Pointer(&lpTotalNumberOfBytes)),
        uintptr(unsafe.Pointer(&lpTotalNumberOfFreeBytes)))
}

你可能感兴趣的:(在Golang中获取系统的磁盘空间内存占用)