syslog函数及syslog配置

syslog函数原型

       #include <syslog.h>

       void openlog(const char *ident, int option, int facility);       

    void syslog(int priority, const char *format, ...);       

     void closelog(void);

       #include <stdarg.h>

       void vsyslog(int priority, const char *format, va_list ap);


 1 #include<stdio.h> 2 #include<sys/types.h> 3 #include<unistd.h> 4 #include<signal.h> 5 #include<sys/param.h> 6 #include<sys/stat.h> 7 #include<time.h> 8 #include<syslog.h> 9 10 int init_daemon(void) 11 { 12 13 int pid; 14 int i; 15 16 signal(SIGTTOU,SIG_IGN); 17 signal(SIGTTIN,SIG_IGN); 18 signal(SIGTSTP,SIG_IGN); 19 signal(SIGHUP,SIG_IGN); 20 21 pid = fork(); 22 if(pid > 0) 23 { 24 exit(0); // 结束父进程,使得子进程成为后台进程 25 } 26 else if(pid < 0) 27 { 28 return -1; 29 } 30 //建立一个新时进程组,在这个新的进程组中,子进程成为这个进程组的首进程,以使该进程脱离所有终端 31 setsid(); 32 /* 再次新建一个子进程,退出父进程,保证该进程不是进程组长,同时让该进程无法打开一个新的终端*/ 33 pid = fork(); 34 if(pid > 0) 35 { 36 exit(0); 37 } 38 else if(pid < 0) 39 { 40 return -1; 41 } 42 /*关闭所有从父进程继承的再需要的文件描述符*/ 43 for(i=0 ; i < NOFILE ; close(i++)); 44 45 /*改变工作目录,使得进程不与任何文件系统联系*/ 46 chdir("/"); 47 48 /*将文字屏蔽字设置为 0*/ 49 50 umask(0); 51 52 /*怱略SIGCHLD信号*/ 53 signal(SIGCHLD,SIG_IGN); 54 return 0; 55 } 56 57 58 int main() 59 { 60 time_t now; 61 init_daemon(); 62 syslog(LOG_USER|LOG_INFO,"测试守护进程! \n"); 63 while(1) 64 { 65 sleep(8); 66 time(&now); 67 syslog(LOG_USER|LOG_INFO,"系统时间:\t%s\t\t\n",ctime(&now)); 68 } 69 }

 注意:在使用syslog前,需要首先配置 /etc/syslog.conf(在linux版本中 /etc/rsyslog.conf) ,在文件的最后一行中加入

user.*  /var/log/test.log,然后重新启动syslog服务,命令分别如下: /etc/init.d/syslog stop(或者/etc/init.d/rsyslog stop)  /etc/init.d/syslog start(或者/etc/init.d/rsyslog start)

 

具体关于syslog配置请参考以下资料

http://www.lvtao.net/server/linux-syslog.html

http://blog.csdn.net/needle2/article/details/6826523

 

  

 

 

 

posted on 2015-07-18 16:49  Banting  阅读(679)  评论(0编辑  收藏  举报

导航