opensolaris下如何取得系统启动时间

来源:互联网 发布:php音频文件上传代码 编辑:程序博客网 时间:2024/06/12 00:13

因为同uptime命令获得的时间没有秒,所以只能自己写一个了;

具体的实现可参见:

http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/cmd/w/w.c

 

总的思路就是读取UTMPX_FILE,取出其中ut_type为BOOT_TIME用户的ut_xtime,

然后用now减去ut_xtime,就是系统启动时间了;

 

static long getSysUpTime(void)
{
    struct stat sbuf;
    size_t size = 0;

    struct utmpx *ut;
    struct utmpx *utmpbegin;
    struct utmpx *utmpend;
    struct utmpx *utp;

    time_t now = 0;
    time_t uptime = 0;

    //read the UTMP_FILE (contains information about each logged in user)
    if (stat(UTMPX_FILE, &sbuf) == -1) {
        printf("read /etc/utmpx file error.");
        exit(1);
    }

    //get the entry number in UTMPX_FILE;
    int entries = sbuf.st_size / sizeof (struct futmpx);
    size = sizeof (struct utmpx) * entries;
    //malloc memory to store info from UTMPX_FILE;
    if ((ut = malloc(size)) == NULL) {
        printf("malloc error when create ut info;");
        exit(1);
    }

    //prepare to iterator UTMPX_FILE;
    (void) utmpxname(UTMPX_FILE);

 

    //iterator UTMPX_FILE

    utmpbegin = ut;
    utmpend = (struct utmpx *)((char *)utmpbegin + size);


    setutxent();
    while ((ut < utmpend) && ((utp = getutxent()) != NULL))
        (void) memcpy(ut++, utp, sizeof (*ut));
    endutxent();

    //get current time;
    (void) time(&now);
    //iterator utmp entry in memory;
    for (ut = utmpbegin; ut < utmpend; ut++)
    {
        if (ut->ut_type == BOOT_TIME)
        {
            //this entry is boot_time, so get uptime with now;
            uptime = now - ut->ut_xtime;
        }
    }

        printf("%f", uptime);
    //time is sencond * 100;
    return uptime*100;
}

原创粉丝点击