How to log time in Linux? (C Programming)

本文介绍了一个使用C语言编写的简单日志记录程序。该程序利用了time、gmtime及asctime等函数来获取并格式化当前的时间,并将时间信息与预定义的日志消息一起打印出来。此外,程序通过sleep函数实现每10秒记录一次日志。

 

#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

/* time, gmtime, asctime */
static void log_time()
{
        struct tm *current_time = NULL;
        char *time_string = NULL;
        time_t t = time(NULL);
        current_time = gmtime(&t); /* the return value of gmtime is statically allocated, no need for free */
        assert(current_time != NULL);
        time_string = asctime(current_time);
        assert(time_string != NULL);
        printf("%s\tsome event here ...\n", time_string);
}

int main(int argc, char *argv[])
{
        for (;;)
        {
                log_time();
                sleep(10);
        }
        exit(EXIT_SUCCESS);
}

 

root@localhost :/home/James/mypro/Linux-Pro/daemon# ./log_time
Wed Jun 13 06:27:48 2012
        some event here ...
Wed Jun 13 06:27:58 2012
        some event here ...
Wed Jun 13 06:28:08 2012
        some event here ...

 

 

 

 

 

 

 

转载于:https://my.oschina.net/u/158589/blog/62177

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值