【问题标题】:Linux get system time since power on自开机以来Linux获取系统时间
【发布时间】:2013-07-18 15:46:16
【问题描述】:

我需要找到系统时间,因为我的 c 代码中的 linux 机器上电。 'time()' 和 gettimeofday() 之类的函数返回自纪元以来的时间,而不是自开机以来的时间。 如何找到开机后的时间或时钟滴答数?

提前致谢!

【问题讨论】:

标签: c linux time


【解决方案1】:

此信息通过/proc 文件系统API 提供。具体来说,/proc/uptime。在 C 语言中,只需将其作为普通文件打开并从中读取一个浮点数。这将是自开机以来的秒数。如果您读取另一个 FP 值,它将是系统总共花费了多少秒处于空闲状态。不过,您只对第一个数字感兴趣。

例子:

float uptime;
FILE* proc_uptime_file = fopen("/proc/uptime", "r");
fscanf(proc_uptime_file, "%f", &uptime);

此值以秒为单位,浮点数。

您可以将其转换回时钟刻度:

uptime * sysconfig(_SC_CLK_TCK);

【讨论】:

  • 我正要提出同样的建议...... :)
【解决方案2】:

见:Wgat API do I call to get the System Time

请参阅

中的 sysinfo()

sys/sysinfo.h

struct sysinfo {
  long uptime;             /* Seconds since boot */
  unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
  unsigned long totalram;  /* Total usable main memory size */
  unsigned long freeram;   /* Available memory size */
  unsigned long sharedram; /* Amount of shared memory */
  unsigned long bufferram; /* Memory used by buffers */
  unsigned long totalswap; /* Total swap space size */
  unsigned long freeswap;  /* swap space still available */
  unsigned short procs;    /* Number of current processes */
  unsigned long totalhigh; /* Total high memory size */
  unsigned long freehigh;  /* Available high memory size */
  unsigned int mem_unit;   /* Memory unit size in bytes */
  char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
};

【讨论】:

    【解决方案3】:

    如果你想了解 C API,

    这个问题可能与What API do I call to get the system uptime?重复

    如果您想通过 shell 了解正常运行时间,请使用 uptime 命令。

    $uptime
    

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多