linux getuptime 系统启动时间

 

 

package webtest

/*
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <stdlib.h>
*/
import "C"

import (
"fmt"
"io/ioutil"
"strconv"
"strings"
"time"
)

var (
Uptime int64 // 系统启动时间戳
scClkTck = int64(C.sysconf(C._SC_CLK_TCK))
)


func Init() {
buf, err := ioutil.ReadFile("/proc/uptime")
Uptime = time.Now().Unix()
if err != nil {
fmt.Println("read file /proc/uptime faile 1")
}
if fields := strings.Fields(string(buf)); len(fields) == 2 {
start, err := strconv.ParseFloat(fields[0], 10)
if err == nil {
Uptime = time.Now().Unix() - int64(start)//- sys.Uptime
}else{
fmt.Println("read file /proc/uptime faile 2")
}
}
}

func ProcessStartTime(pid int) (ts time.Time) {
buf, err := ioutil.ReadFile(fmt.Sprintf("/proc/%v/stat", pid))
if err != nil {
return time.Unix(0, 0)
}
if fields := strings.Fields(string(buf)); len(fields) > 22 {
start, err := strconv.ParseInt(fields[21], 10, 0)
if err == nil {
if scClkTck > 0 {
return time.Unix(Uptime+(start/scClkTck), 0)
}
return time.Unix(Uptime+(start/100), 0)
}
}
return time.Unix(0, 0)
}

 

 

 

 

 

 

 

 

参考:

https://coding3min.com/597.html

 

posted @   redrobot  阅读(113)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示