編寫守護進程,並使用守護進程按要求生成.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	
<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 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”強行結束掉守護進程。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章