日志守护进程实例:(rsyslogd)

日志程进程:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/klog.h>
#include <sys/types.h>
#define BLEN 4096
char buff[BLEN+1]=0;
char * strchrnul(char *str,char c){
    while(*str &&*str!=c) ++str;
    return str;
}
int main(int argc,char *argv[]){
    int len;
    int uitlog;
    uitlog=open("/tmp/uit_syslogd.log",O_RDWR|O_CREAT);
    if(uitlog==-1)
        {
            printf("creat /tmp/uit_syslogd.log failed ! \n");
            return 0;
        }
     lseek(uitlog,0,SEEK_END);  
 klogctl(1,NULL,0);  //open log
                 
     while(1)
     {
        int n;
        char *start;
        start=buff;
        n=klogctl(2,start,BLEN-1); //2 -- Read from the log.
        if(n<0){
            write(uitlog,"logd :error %d return from klogctl ! \n",n);
                break;
           return 0;
        }
       
        start[n]='\0';
        while(1)
        {
            char *newline=strchrnul(start,'\n');
            if(*newline=='\0'){
                newline=NULL;
                break;
            }else{
                *newline='\0';
                  newline++;
            }
            // 去掉消息级别
            /*
                if(*start=='<'){
                    start++;
                    if(*start){
                     level=*start-'0';
                     start++;
                    }
                    if(*start=='>')
                        start++;
                }
            */
            if(*start){
                    write(uitlog,start,newline-start-1);
                    write(uitlog,"\n",1);
                }
            if(!newline) 
                break;
            start=newline;
        }
    
     }
     klogctl(0,NULL,0);  // close log
     return 1;

你可能感兴趣的:(日志守护进程实例:(rsyslogd))