Linux開發--守護進程的創建

1 簡介

    守護進程是在後臺運行不受終端控制的進程,通常情況下守護進程在系統啓動時自動運行,用戶關閉終端窗口或註銷也不會影響守護進程的運行,只能kill掉。守護進程的名稱通常以d結尾,比如sshd、xinetd、crond等

    實際上一般的進程(前後臺) 在關閉終端窗口後,會收到 SIGHUP 信號導致中斷,可以使用 nohup command args > /dev/null 2>&1 & 來忽略 hangup 信號,或者直接使用 setsid command args 來使進程成爲守護進程。需要注意的是,使用 nohup 時的父進程id 爲終端的進程id,使用 setsid 時的父進程id 爲 1(即 init 進程 id)。


2 守護進程的創建

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fs.h>

int main (void)
{
	pid_t pid;
	int i;
	
	/* create new process */
	pid = fork ( );
	if (pid == -1)
		return -1;
		
	else if(pid != 0)
		exit (EXIT_SUCCESS);
		
	/* create new session and process group */
	if (setsid ( ) == -1)
		return -1;

	/* set the working directory to the root directory */
	if (chdir (”/”) == -1)
		return -1;
	
	/* close all open files--NR_OPEN is overkill, but works */
	for (i = 0; i < NR_OPEN; i++)
		close (i);
	
	/* redirect fd’s 0,1,2 to /dev/null */
	open (”/dev/null”, O_RDWR); /* stdin    */
	dup (0);                    /* stdout   */
	dup (0);                    /* stderror */
	
	/* do its daemon thing... */
	
	return 0;
}

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