原文链接:

title: go linux macos 获取磁盘占用
date: 2020-08-13T10:27:23+08:00
lastmod: 2020-08-13T10:27:23+08:00
categories: [golang]
tags: [golang]
url: /language/golang/go-linux-disk-mem-usage

aliases:

markup: mmark


phil-fly/sysinfo: 获取系统信息:cpu 磁盘 内存等

package system

import (
	"syscall"
)

// getSysInfo gets sysinfo.
func getSysInfo() (*syscall.Sysinfo_t, error) {
	si := &syscall.Sysinfo_t{}
	err := syscall.Sysinfo(si)
	if err != nil {
		return nil, err
	}
	return si, nil
}

// GetTotalMem gets total ram of host.
func GetTotalMem() (uint64, error) {
	si, err := getSysInfo()
	if err != nil {
		return 0, err
	}
	return si.Totalram, nil
}

获取磁盘占用情况(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

}

`