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

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	
		Written By Namer_Mega .Thanks For Sharing Your Knowledge
*/

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

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 process
	else if(pid < 0)
		exit(1);
	
	//The second process will not be gip

	for(i = 0;i < getdtablesize();i++)
		close(i);     //Close the open-file descriptor

	chdir("/tmp");   //change work catalogue
	umask(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”强行结束掉守护进程。

你可能感兴趣的:(守护进程,嵌入式Linux程序设计)