Uptime under linux in C

后端 未结 3 1736
说谎
说谎 2021-02-20 05:41

How can I retrieve uptime under linux using C? (without using popen and/or /proc)

Thanks

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-20 06:20

    If its there and contains the member uptime, struct sysinfo is the preferred way to go, as Jack explained.

    The other way is to read btime out of /proc/stat , then just subtract it from the current time. btime is just a UNIX epoch indicating when the kernel booted.

    That gives you the # of seconds since boot, which you can then translate into years / months / days / hours / etc. This saves having to deal with strings in /proc/uptime. If btime isn't there, and struct sysinfo has no member named uptime, you have to parse /proc/uptime.

    For modern kernels, sysinfo() should work just fine. Most things still running 2.4 (or earlier) out in the wild are appliances of some kind or other embedded systems.

提交回复
热议问题