通过在go中嵌入linux命令来获取cpuId,这样做,使该方法具有较高的可复用性,只用通过修改linux指令,就可以在程序中获取linux指令所能获取的任何信息。
运行结果以及完整的源码如下:
package main
import (
"fmt"
"io/ioutil"
"os/exec"
)
type CommPack struct {
//bytesdata byte
bytesData []byte
}
func GET_CPUID() (CommPack,error){
cmd := exec.Command("/bin/sh", "-c", `sudo dmidecode -t 4 | grep ID `)
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Println("StdoutPipe: " + err.Error())
return CommPack{nil},err
}
stderr, err := cmd.StderrPipe()
if err != nil {
fmt.Println("StderrPipe: ", err.Error())
return CommPack{nil},err
}
if err := cmd.Start(); err != nil {
fmt.Println("Start: ", err.Error())
return CommPack{nil},err
}
bytesErr, err := ioutil.ReadAll(stderr)
if err != nil {
fmt.Println("ReadAll stderr: ", err.Error())
return CommPack{nil},err
}
if len(bytesErr) != 0 {
fmt.Printf("stderr is not nil: %s", bytesErr)
return CommPack{nil},err
}
bytes, err := ioutil.ReadAll(stdout)
if err != nil {
fmt.Println("ReadAll stdout: ", err.Error())
return CommPack{nil},err
}
if err := cmd.Wait(); err != nil {
fmt.Println("Wait: ", err.Error())
return CommPack{nil},err
}
return CommPack{bytes},err
}
func main() {
var ds CommPack
ds,_=GET_CPUID()
fmt.Printf("stdout: pid = %s", ds.bytesData)
}