標籤:style io ar color os sp for on 檔案
1、進程組 組長不能建立新的 會話
2、會話首領可以重新開啟控制終端
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <sys/param.h>
5 #include <sys/stat.h>
6 #include <sys/types.h>
7 #include <fcntl.h>
8 #include <signal.h>
9
10 void my_daemon() {
11 int pid, fd;
12
13 // 1.轉變為後台進程
14 if ((pid = fork()) == -1) exit(1);
15 if (pid != 0) exit(0); // 父進程(前台進程)退出
16
17 // 2.離開原先的進程組,會話
18 if (setsid() == -1) exit(1); // 開啟一個新會話
19
20 // 3.禁止再次開啟控制終端
21 if ((pid = fork()) == -1) exit(1);
22 if (pid != 0) exit(0); // 父進程(會話領頭進程)退出
23
24 // 4.關閉開啟的檔案描述符,避免浪費系統資源
25 for (int i = 0; i < NOFILE; i++)
26 close(i);
27
28 // 5.改變當前的工作目錄,避免卸載不了檔案系統
29 if (chdir("/") == -1) exit(1);
30
31 // 6.重設檔案掩碼,防止某些屬性被父進程屏蔽
32 if (umask(0) == -1) exit(1);
33
34 // 7.重新導向標準輸入,輸出,錯誤流,因為守護進程沒有控制終端
35 if ((fd = open("/dev/null", O_RDWR)) == -1) exit(1); // 開啟一個指向/dev/null的檔案描述符
36 dup2(fd, STDIN_FILENO);
37 dup2(fd, STDOUT_FILENO);
38 dup2(fd, STDERR_FILENO);
39 close(fd);
40
41 // 8.本守護進程的子進程若不需要返回資訊,那麼交給init進程回收,避免產生殭屍進程
42 if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) exit(1);
43 }
44
45 #define INTERVAL 2
46
47 int main(int argc, char *argv[]) {
48 my_daemon(); // 首先使之成為守護進程
49
50 int t = 0;
51 FILE *fp = fopen("/root/tmp.txt", "a");
52 fprintf(fp, "ppid = %d, pid = %d, sid = %d, pgrp = %d\n", getppid(), getpid(), getsid(0), getpgrp());
53 fflush(fp);
54
55 do { // 測試此後台進程,每INTERVAL秒列印目前時間t,30秒後退出此後台進程
56 fprintf(fp, "%d\n", t);
57 fflush(fp); // 輸出緩衝區內容到檔案中
58 sleep(INTERVAL);
59 t += INTERVAL;
60 } while(t < 30);
61
62 fclose(fp);
63
64 return 0;
65 }
儲存為daemon.c
編譯命令 gcc daemon.c
運行 ./a.out
查看tmp.txt檔案內容 cat /root/tmp.txt
linux 守護進程(daemon process)代碼-詳細注釋