怎么判断linux进程有异常,linux进程开发之(七):守护进程出错判断

#include#include#include#include#include#include#include#include

#define MAXFILE 65536

int main()

{

pid_t pc,sid;

int i,fd,len;

char *buf="this is a dameon\n";

len=strlen(buf);

pc=fork();

if(pc<0)

{

printf("error fork\n");

exit(1);

}

else if(pc>0)

{

exit(0);

}

openlog("demo_update",LOG_PID,LOG_DAEMON);//打开系统日志

if((sid=setsid())<0)

{

syslog(LOG_ERR,"%s\n","setsid");

exit(1);

}

if((sid=chdir("/"))<0)

{

syslog(LOG_ERR,"%s\n","chdir");

exit(1);

}

umask(0);

for(i=0;i{

close(i);

}

while(1)

{

if((fd=open("/tmp/dameon.log",O_CREAT|O_WRONLY |O_APPEND,0600))<0)

{

syslog(LOG_ERR,"open");//打开守护进程的日志文件,并写入open的日志记录

exit(1);

}

write(fd,buf,len+1);

close(fd);

sleep(10);

}

closelog();

exit(0);

}

/*-------------------------------------------

1.守护进程的出错处理

使用syslog服务,将程序中的出错信息输入到"/var/log/message"系统日志中,从而可以直观

地看到程序的问题所在.

syslog是linux中的系统日志管理服务,通过守护进程syslogd来维护。该守护进程在启动时会

读一个培植文件"/etc/syslog.conf".该文件决定了不同种类的消息会发送向何处。

该机制提供了3个syslog函数,分别为openlog,syslog和closelog.

2.opnelog函数语法

1)所需要的头文件

#include2)函数原型

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

3)输入参数

ident:要向每个消息加入字符串,通常为程序的名称

option:

LOG_CONS:如果消息无法送到系统日志服务,则直接输出到系统控制终端

LOG_NDELAY:立即打开系统日志服务的连接,在正常情况下,直到发送到第一条消息时才

打开连接

LOG_PERROR:将消息也同时送到stderr

LOG_PID:在每条消息中包含进程的PID

facility:

LOG_AUTHPRIV:安全/授权讯息

LOG_CRON:时间守护进程(cron及at)

LOG_DAEMON:其他系统守护进程

LOG_KERN:内核信息

LOG_LOCAL[0-7]:保留

LOG_LPR:行打印机子系统

LOG_MAIL:邮件子系统

LOG_NEWS:新闻子系统

LOG_SYSLOG:syslogd内部所产生的信息

LOG_USER:一般使用者等级讯息

LOG_UUCP:UUCP子系统

3.syslog函数语法

1)所需头文件:#include2)函数原型:void syslog(int priority,char *format,...)

3)函数输入参数

priority

LOG_EMERG:系统无法使用

LOG_ALERT:需要立即采取措施

LOG_CRIT:有错误发生

LOG_WARNING:有警告发生

LOG_NOTICE:正常情况,但也是重要情况

LOG_INFO:信息消息

LOG_DEBUG:调试信息

format:以字符串指针的形式表示输出的格式,类似printf中的格式

4.closelog

1)所需头文件 #include2)函数原型:void closelog(void)

----------------------------------------------*/

实验

1.

[root@localhost the_seventh_step]# gcc syslog_dema.c -o syslog_dema

2.

[root@localhost the_seventh_step]# tail -f /tmp/dameon.log

this is a Dameon

this is a Dameon

this is a Dameon

this is a Dameon

this is a Dameon

this is a Dameon

this is a Dameon

this is a Dameon

this is a Dameon

3.

[root@localhost the_seventh_step]# ps -ef |grep dameon

root      5954  3363  0 16:25 pts/1    00:00:00 grep dameon

4.

cat /var/log/message

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值