LALA |
|
|||
日歷
導航留言簿(1)隨筆分類(31)
文章分類(4)收藏夾(21)搜索積分與排名
最新隨筆
最新評論
閱讀排行榜 |
守護進程運行在后臺,不與任何控制終端相關聯.守護進程以root用戶運行或者其他特殊的用戶,并處理一些系統級的任務, 習慣上守護進程的名字以d結尾,但不是必須的.
對守護進程的兩個基本要求: 它必須是init進程的子進程; 不與任何控制終端相關聯.
一般來講, 進程可以通過以下步驟成為守護進程:
根據這些規則, 下面程序可以成為守護進程:
1 #include<sys/types.h>
2 #include<sys/stat.h> 3 #include<stdlib.h> 4 #include<stdio.h> 5 #include<fcntl.h> 6 #include<unistd.h> 7 #include<linux/fs.h> 8 9 int main(void) 10 { 11 pid_t pid; 12 int i; 13 /* create new process */ 14 pid = fork(); 15 if(pid == -1) return -1; 16 else if(pid != 0) exit(EXIT_SUCCESS); 17 /* create new session and process group */ 18 if(setsid() == -1) return -1; 19 /* set the working directory to the root directory*/ 20 if(chdir("/") == -1) return -1; 21 /* close all open files -- NR_OPEN is overkill, but works */ 22 for(i = 0; i < NR_OPEN; i++) close(i); 23 /* redirect fd's 0, 1, 2 to /dev/null */ 24 open("/dev/null", O_RDWR); /* stdin */ 25 dup(0); /* stdout */ 26 dup(0); /* stderr */ 27 /* do it daemon thing ![]() 28 29 return 0; 30 } 許多Unix系統在它們的C函數庫中提供了daemon()函數來完成這些工作:
#include <unistd.h>
int daemon(int nochdir, int noclose);
|
![]() |
|
Copyright © Dest | Powered by: 博客園 模板提供:滬江博客 |