• 日志文件实时存储


    初始化:
    1、open文件
    2、write 1M空数据到文件
    3、mmap文件,ptr作为写指针
    4、关闭文件

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #include <string.h>
    #include <sys/syscall.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <errno.h>
    #include <sys/mman.h>
    
    
    
    #define XLOG_MAX_FILE_SIZE  32*1024
    
    char *xlog_write_ptr = NULL;
    int xlog_write_size = 0;
    int xlog_fd = -1;
    
    int inner_id = 0;
    char xlog_path_name[128] = "/home/derek";
    
    int xlog_set_path_name(char *path_name)
    {
        if(strlen(path_name) > 64 || path_name == NULL) return 1;
    
        sprintf(xlog_path_name, "%s", path_name);
            
        return 0;
    }
    
    int xlog_file_restore(int mid)
    {
        int fd;
        char file_name[128];
        char *temp_buff;
    
        //flush to file
        if ( xlog_write_ptr != NULL) munmap(xlog_write_ptr, XLOG_MAX_FILE_SIZE);
        
        sprintf(file_name, "%s/xlog%d.%d.txt", xlog_path_name, mid, inner_id++);
        
        fd = open(file_name, O_RDWR|O_CREAT);
        if(fd < 0) {
            printf("open: %s
    ", strerror(errno));
            return 1;
        }
    
        temp_buff = malloc(XLOG_MAX_FILE_SIZE);
        if (temp_buff == NULL) {
            printf("malloc: %s
    ", strerror(errno));
            return 1;
        }
    
        memset(temp_buff, 0, XLOG_MAX_FILE_SIZE);
        write(fd, temp_buff, XLOG_MAX_FILE_SIZE);
        free(temp_buff);
    
        xlog_write_ptr = mmap(0, XLOG_MAX_FILE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);  
        if (xlog_write_ptr == (char *)-1) {
            printf("mmap: %s
    ", strerror(errno));
            return 1;
        }
        printf("xlog_write_ptr=0x%x
    ", xlog_write_ptr);
        xlog_write_size = 0;
    
        close(fd);
        return 0;
    }
    
    
    
    int xlog_buffer(int mid, char *buffer)
    {
        char log_info[128];
        int str_len = strlen(buffer);
        
        if ( (xlog_write_size + str_len > XLOG_MAX_FILE_SIZE) || (xlog_write_ptr == 0) )
        {
            if ( xlog_file_restore(mid) < 0) 
                return 1;
        }
    
        // write to buffer
        sprintf(xlog_write_ptr + xlog_write_size, "%s", buffer);
        xlog_write_size += str_len;
        
        return 0;
    }
    
    int main()
    {
        int i;
        char log_info[128];
        
        for(i = 0; i < 100000; i++) {
            sprintf(log_info, "hello, %d
    ", i);
            xlog_buffer(1, log_info);
            //sleep(1);
        }
        
        return 0;
    }
  • 相关阅读:
    asp.net中常用提示对话框
    winForm 常用总结
    C#的IS和AS运算符区别
    转 七种武器——.NET工程师求职面试必杀技
    C#中bool与Boolean有什么区别?string和String区别?
    转 面向程序员的数据库访问性能优化法则
    转:回音消除技术
    转C#中using和new的用法
    转 C# 性能优化之斤斤计较篇
    转:三种运行Powershell代码的方法
  • 原文地址:https://www.cnblogs.com/soul-stone/p/6688740.html
Copyright © 2020-2023  润新知