linux 的core file的时间戳怎么样才能变成日期格式

linux 程序崩溃之后会产生core file,带有时间戳,但是时间戳总是不是很直观,每次都要转换下才能知道是什么时候产生的,怎么样才能让生成的core文件的时间戳变成日期格式,如20160911
这样的

自己写代码...

先修改 /proc/sys/kernel/core_pattern

|/sbin/genCore %p %t 
  • %p - 获取crash 进程号,也能获取crash进程所在的路径
  • %t - 时间戳,用于转换成Y/m/d格式

genCore的源代码如下,会在crash进程同一目录下生成core.pid.MYD格式的coredump.

genCore.c


#define _GNU_SOURCE
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

#define BUF_SIZE 1024
#define FILENAME_MAX_LENGTH 256
#define TIMESTAMP_MAX_LENGTH 20

int
main(int argc, char *argv[])
{
    int tot, j;
    ssize_t nread;
    char buf[BUF_SIZE];
    FILE *fp;
    char cwd[PATH_MAX];

    char fileName[FILENAME_MAX_LENGTH];
    char strTimeStamp[TIMESTAMP_MAX_LENGTH];
    struct tm *coreTimeStamp;
    time_t rawTimeStamp;

    /* Change our current working directory to that of the
       crashing process */
    snprintf(cwd, PATH_MAX, "/proc/%s/cwd", argv[1]);
    chdir(cwd);

    /* Write output to file "core.<pid>.<Ymd>" in that directory */
    rawTimeStamp = (time_t) (atoi(argv[2]));
    coreTimeStamp = localtime(&rawTimeStamp);
    strftime(strTimeStamp, TIMESTAMP_MAX_LENGTH,"%Y%m%d",coreTimeStamp);
    snprintf(fileName, FILENAME_MAX_LENGTH, "core.%s.%s", argv[1], strTimeStamp);
    fp = fopen(fileName, "w+");

    if (fp == NULL)
        exit(EXIT_FAILURE);

    /* Dump the core dump to file */
    while ((nread = read(STDIN_FILENO, buf, BUF_SIZE)) > 0)
        fwrite(buf, nread, 1, fp);

    fclose(fp);
    exit(EXIT_SUCCESS);
}

那是个标准的时间戳,除非你自己修改内核dump的代码,做一些转换。或者用工具将文件名重新计算改一下。