LoginSignup
2
3

More than 5 years have passed since last update.

[linux] システム起動時間を取得するサンプルコード

Posted at

uptimeコマンドで確認できる、Linuxシステムが起動してからの時間をC言語のコードから取得できるようにする

uptimeコマンドの実行例
$ uptime
 16:35:03 up  7:39, 11 users,  load average: 0.00, 0.00, 0.00

/proc/uptime の中を見ると以下のように、二つの値が取得できる

/proc/uptimeの取得例
$ cat /proc/uptime
27118.96 189325.22

このうち、左から1番目の値が起動からの秒数でuptimeコマンドで取得できる値である。2番目はアイドル時間である。1番目の値を取得するようにコードを書けばよい

サンプルコード
//#include <stdio.h>  // printfしたければinclude
#include <stdlib.h>  // strtof
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <locale.h>

/**
 * Linuxの起動時間を取得する
**/
time_t
getLinuxUptime()
{
    int fd;
    char buf[64];
    char *endptr, *saveptr;
    ssize_t len;
    time_t get_time = 0;
    char *savelocale;

    fd = open("/proc/uptime", O_RDONLY);
    if (fd < 0){
//        printf("cannot open proc uptime: %s", strerror(errno));
        return 0;
    }
    lseek(fd, 0L, SEEK_SET);

    savelocale = strdup(setlocale(LC_NUMERIC, NULL));
    if (savelocale) {
        setlocale(LC_NUMERIC,"C");
    }

    len = read(fd, buf, sizeof(buf)-1);
    if (len < 0) {
        buf[0] = '\0';
//        printf("cannot read proc uptime: %s", strerror(errno));
    } else {
        buf[len] = '\0';
    }

    if (savelocale) {
        setlocale(LC_NUMERIC, savelocale);
        free(savelocale);
    }

    close(fd);

    if (strtok_r(buf, " ", &saveptr) != NULL) {
        get_time = (time_t)strtof(buf, &endptr);
        if (*endptr != '\0') {
//            printf("linux uptime parse miss. buffer=%s", buf);
        }
    }

//    printf("Linux Uptime: %lu\n", (unsigned long)get_time);

    return get_time;
}

procps-ngのコードが参考になった
https://gitlab.com/procps-ng/procps

ソースを見て初めて知ったのだが、uptimeの"-s"オプションを指定するとシステムを起動した時間が分かる。

実行例
$ uptime -s
2017-08-18 08:55:20

※ 現在時刻を基準に算出しているので、コマンド実行時に正しい時刻が設定されていることが前提

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3