编写守护进程,并使用守护进程按要求生成.log文件

来源:互联网 发布:wps怎么合计数据 编辑:程序博客网 时间:2024/05/17 01:11

1.编写一守护进程,每隔30秒,将系统当前进程总数、休眠进程数、运行进程数、僵死进程数、终止进程数等信息按照如下格式写入到procinfo.log文件中。

格式可类似为:

2013-11-10 20:50:20
29 processes: 28 sleeping, 1 running, 0 zombie, 0 stopped
2013-11-10 20:50:50

29 processes: 28 sleeping, 1 running, 0 zombie, 0 stopped


/*Exp 9_1 :Create finger daemonfinger Main.c
<span style="white-space:pre"></span>Written By Namer_Mega .Thanks For Sharing Your Knowledge*/#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <signal.h>#include <sys/param.h>#include <sys/types.h>#include <sys/stat.h>#include <time.h>void init_deamon(void){int pid;int i;/*处理Sigchld信号*/if(signal(SIGCHLD,SIG_IGN) == SIG_ERR){printf("Can't signal in init_daemon\n");exit(1);}pid = fork(); //创建进程if(pid){printf("It's a father process\n");//父进程exit(0);}else if(pid ==0){printf("It's a first child process.Normal\n");}else if(pid < 0){perror("Failed to create process\n");exit(1);  //创建失败}/*得到第一子进程,后台继续执行*/setsid(); //第一子今晨成为新的绘画组长和进程组长//并与控制终端分离if(pid = fork())exit(0); //terminal first child processelse if(pid < 0)exit(1);//The second process will not be gipfor(i = 0;i < getdtablesize();i++)close(i);     //Close the open-file descriptorchdir("/tmp");   //change work catalogueumask(0); //system("date > /tmp/procinfo.txt");for(i = 0;i< 10;i++){sleep(1);system("date >>/tmp/procinfo.log\n");system("ps >>/tmp/procinfo.log\n");}return ; }/* Main Function*/int main(void){//void init_deamon(void);//FILE *fp;//time_t t;init_deamon();     /*while(1)//每隔一分钟向test.log报告运行状态     {         sleep(3);//睡眠一秒钟         if((fp=fopen("procinfo.log","a")) >=0)         {             t=time(0);             fprintf(fp,"The time right now is : %s\n",asctime(localtime(&t))); //fprintf(fp,top);            fclose(fp);         }     }*/    return 0;}


注意 :收据进程一旦创建,自然情况下只能随操作系统关闭而关闭,也就是说关闭终端后守护进程仍在运行。

如果你对代码进行了修改,重新编译后运行前,请调用“top”命令查看当前所有进程,找到你创建的守护进程并用“kill + uid”强行结束掉守护进程。

0 0
原创粉丝点击