dmesg列印資訊如何後台儲存到檔案中

來源:互聯網
上載者:User

         dmesg調試i資訊常常作為判斷系統異常退出的重要訊息,但是當個系統異常退出或重啟時,資訊又難以儲存下來,於是才有了將dmesg調試資訊儲存到檔案中的想法:

#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <time.h>//#include <linux/autoconf.h>//核心編譯的配置資訊#include <sys/klog.h>#include <sys/stat.h>//#define __LOG_BUF_LEN   (1 << CONFIG_LOG_BUF_SHIFT)//在2.6.28核心中為預設1<<17,這才是真正dmesg buffer的大小,網上其他都扯淡。#define __LOG_BUF_LEN   (1 << 17)//在2.6.28核心中為預設1<<17,這才是真正dmesg buffer的大小,網上其他都扯淡。#define __LOG_PATH      "/home/default/dmesg.log"#define LOG_SLEEP(x)    (sleep(x))#define __LOG_SIZE      10485760//大於10M時刪除檔案#define BUF_SIZE        256long check_log_size(void){struct stat f_stat;if( stat( __LOG_PATH, &f_stat ) == -1 ){return -1;}return (long)f_stat.st_size;}int main(int argc, char *argv[]){char buf[__LOG_BUF_LEN]={0,};char tmpbuf[BUF_SIZE]={0,};int ret = 0;FILE *fp =NULL;struct tm *ptr;time_t lt;//daemon(0,0);//進入守護模式while(1){LOG_SLEEP(120);//sleep 10 秒fp = fopen(__LOG_PATH,"a+");//追加開啟if(NULL == fp){printf("creat file faild !\n");continue;}ret = klogctl(4,buf,__LOG_BUF_LEN);//獲得dmesg資訊,該函數需要超級使用者權限運行if(0 >= ret){perror("klogctl ");fclose(fp);continue;}lt = time(NULL);//獲得時間ptr = (struct tm *)localtime(<);sprintf(tmpbuf,"       [LOG TIME:]       %s",asctime(ptr));//記錄時間printf("tmpbuf = %s\n",tmpbuf);fwrite(tmpbuf,strlen(tmpbuf),1,fp);fwrite(buf,strlen(buf),1,fp);fflush(fp);fclose(fp);if(__LOG_SIZE < check_log_size()){unlink(__LOG_PATH);//刪除該檔案}memset(tmpbuf,0,BUF_SIZE);memset(buf,0,__LOG_BUF_LEN);}return 0;}

以下是Makefil

CC := arm-none-linux-gnueabi-gccall:dmesg_testdmesg_test:dmesg_test.c$(CC) dmesg_test.c -o dmesg_test -Wallinstall:cp dmesg_test /nfsroot/updateclean:rm dmesg_test

運行:dmesg_test &

程式就進入後台執行了,每隔120秒會讀取一次dmesg資訊。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.