1. 守護進程是什麼mysql
2.1 有趣小例子sql
3. 源碼解析api
3.2 daemon.c 解析session
3.3 BUGSapp
4. 後記ide
Linux Daemon (守護進程) 是運行在後臺的一種特殊進程. 它獨立於控制終端而且週期性地執行某種任務或等待處理函數
某些發生的事件. 不依賴用戶輸入就能提供某種服務.
Linux 系統中大多數服務都是經過守護進程實現的. 常見的守護進程包括系統日誌進程 syslogd, Web 服務器 httpd ,
MySQL 數據庫服務器 mysqld 等. 守護進程的命名咱們一般約定以 d 結尾.
#include <time.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> // // gcc -g -O2 -Wall -Wextra -o demo demo.c // int main(void) { // 建立守護進程 if (daemon(0, 0)) { perror("daemon error"); exit(EXIT_FAILURE); } // 守護進程 構建文本任務 FILE * txt = fopen("demo.log", "w"); if (txt) { fprintf(txt, "%ld, hello, 世界", time(NULL)); fclose(txt); } exit(EXIT_SUCCESS); }
結果出人意料呢? daemon(0, 0) ~ 經過 GNU C 庫 提供的 api, 輕巧的建立了守護進程.
有心同行也能夠將上面素材當作守護進程面試題, 不須要死記硬背, 簡單交流下就能夠考察出候選人是否嚴謹和用心.
全貌瞭解 daemon() 函數最簡單方法仍是看 man daemon 手冊, 摘錄些一塊學習學習, 溫故溫故.
DAEMON(3) Linux Programmer's Manual DAEMON(3) NAME daemon - run in the background SYNOPSIS #include <unistd.h> int daemon(int nochdir, int noclose); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): daemon(): Since glibc 2.21: _DEFAULT_SOURCE In glibc 2.19 and 2.20: _DEFAULT_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500) Up to and including glibc 2.19: _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500) DESCRIPTION The daemon() function is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons. If nochdir is zero, daemon() changes the process's current working directory to the root directory ("/"); otherwise, the current working directory is left unchanged. If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors. RETURN VALUE (This function forks, and if the fork(2) succeeds, the parent calls _exit(2), so that further errors are seen by the child only.) On suc‐ cess daemon() returns zero. If an error occurs, daemon() returns -1 and sets errno to any of the errors specified for the fork(2) and set‐ sid(2). ATTRIBUTES For an explanation of the terms used in this section, see attributes(7). ┌──────────┬───────────────┬─────────┐ │Interface │ Attribute │ Value │ ├──────────┼───────────────┼─────────┤ │daemon() │ Thread safety │ MT-Safe │ └──────────┴───────────────┴─────────┘ CONFORMING TO Not in POSIX.1. A similar function appears on the BSDs. The daemon() function first appeared in 4.4BSD. NOTES The glibc implementation can also return -1 when /dev/null exists but is not a character device with the expected major and minor numbers. In this case, errno need not be set. BUGS The GNU C library implementation of this function was taken from BSD, and does not employ the double-fork technique (i.e., fork(2), set‐ sid(2), fork(2)) that is necessary to ensure that the resulting daemon process is not a session leader. Instead, the resulting daemon is a session leader. On systems that follow System V semantics (e.g., Linux), this means that if the daemon opens a terminal that is not already a controlling terminal for another session, then that terminal will inadvertently become the controlling terminal for the daemon. SEE ALSO fork(2), setsid(2), daemon(7), logrotate(8) COLOPHON This page is part of release 4.15 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at https://www.kernel.org/doc/man-pages/. GNU 2017-11-26 DAEMON(3)
翻譯其中核心的幾小段, 有更好翻譯能夠提供或者告知, 文章會迅速修正.
NAME daemon - 運行在後臺 SYNOPSIS #include <unistd.h> int daemon(int nochdir, int noclose); DESCRIPTION daemon() 函數但願運行程序脫離控制終端, 做爲系統守護進程在後臺運行. 若是 nochdir 是 0, daemon() 將更改當前進程工做目錄到 "/" 根目錄. 不然保持 不變. 若是 noclose 是 0, deamon() 將重定向 STDIN_FILENO 標準輸入, STDOUT_FILENO 標準輸出, STDERR_FILENO 標準錯誤 到 /dev/null, 不然保持不變. RETURN VALUE 函數內部會執行 fork, 若是 fork 成功, 父進程會調用 _exit 退出. 執行成功返回 0. 發生錯誤時候將返回 -1, errno 的設置依賴 fork(), setsid(), daemon() 源碼.
glibc-2.33/misc/daemon.c
1 /*- 2 * Copyright (c) 1990, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 4. Neither the name of the University nor the names of its contributors 14 * may be used to endorse or promote products derived from this software 15 * without specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27 * SUCH DAMAGE. 28 */ 29 30 #if defined(LIBC_SCCS) && !defined(lint) 31 static char sccsid[] = "@(#)daemon.c 8.1 (Berkeley) 6/4/93"; 32 #endif /* LIBC_SCCS and not lint */ 33 34 #include <errno.h> 35 #include <fcntl.h> 36 #include <paths.h> 37 #include <unistd.h> 38 #include <sys/stat.h> 39 40 #include <device-nrs.h> 41 #include <not-cancel.h> 42 43 int 44 daemon (int nochdir, int noclose) 45 { 46 int fd; 47 48 switch (__fork()) { 49 case -1: 50 return (-1); 51 case 0: 52 break; 53 default: 54 _exit(0); 55 } 56 57 if (__setsid() == -1) 58 return (-1); 59 60 if (!nochdir) 61 (void)__chdir("/"); 62 63 if (!noclose) { 64 struct stat64 st; 65 66 if ((fd = __open_nocancel(_PATH_DEVNULL, O_RDWR, 0)) != -1 67 && (__builtin_expect (__fstat64 (fd, &st), 0) 68 == 0)) { 69 if (__builtin_expect (S_ISCHR (st.st_mode), 1) != 0 70 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR 71 && (st.st_rdev 72 == makedev (DEV_NULL_MAJOR, DEV_NULL_MINOR)) 73 #endif 74 ) { 75 (void)__dup2(fd, STDIN_FILENO); 76 (void)__dup2(fd, STDOUT_FILENO); 77 (void)__dup2(fd, STDERR_FILENO); 78 if (fd > 2) 79 (void)__close (fd); 80 } else { 81 /* We must set an errno value since no 82 function call actually failed. */ 83 __close_nocancel_nostatus (fd); 84 __set_errno (ENODEV); 85 return -1; 86 } 87 } else { 88 __close_nocancel_nostatus (fd); 89 return -1; 90 } 91 } 92 return (0); 93 }
30-32 行 SCCS ID (SCCS 表明源代碼控制系統)
66 行 和 88 行 相似 open 和 close
// sysdeps/generic/not-cancel.h /* By default we have none. Map the name to the normal functions. */ #define __open_nocancel(...) \ __open (__VA_ARGS__) #define __close_nocancel(fd) \ __close (fd)
不過 88 行不夠嚴禁, 由於當 fd == -1 時候, 會 __close_nocancel_nostatus (-1) 會引起一個 @errno{EBADF, 9, Bad file descriptor}.
67 - 73 行 (__builtin_expect (EXP, N) 表達意思是告訴編譯器預測 EXP 表試式 == 常量 N 機率很大, 返回值是 EXP ) 大體
意思獲取文件屬性, 而且不是字節設備. makedev 用於構建設備 id.
75-77 三行, 將 STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO 句柄指向 fd 句柄所指向的 dev/null 文件.
78-79 行, 很漂亮很嚴謹功力很厚.
在 2.2 中有這段話,
BUGS The GNU C library implementation of this function was taken from BSD, and does not employ the double-fork technique (i.e., fork(2), set‐ sid(2), fork(2)) that is necessary to ensure that the resulting daemon process is not a session leader. Instead, the resulting daemon is a session leader. On systems that follow System V semantics (e.g., Linux), this means that if the daemon opens a terminal that is not already a controlling terminal for another session, then that terminal will inadvertently become the controlling terminal for the daemon. BUGS GNUC 庫 這個 daemon() 函數的實現取自 BSD 源碼. 沒有采用兩次 double fork 設置 sid 機制, 來確保生成的守護進程不是會話負責人. 相反, 這裏生成的守護 進程是會話負責人 (session leader). 在遵循 System V 語義系統上, 建立的守 護進程在從新打開終端時候, 新開終端會自動成爲守護進程的控制終端.
參照這些內容咱們補充一個大體符合 System V 版本 daemon
/* * 建立守護進程 */ void daemon_service(void) { // fork 後父進程 exit 退出, 保證子進程能夠成功 setsid() 擁有一個新會話 switch (fork()) { case -1: exit(EXIT_FAILURE); case 0: break; default: exit(EXIT_SUCCESS); } // 子進程建立新會話 // 執行成功後 Process ID(PID) == Process Group ID(PGID) == Session ID(SID) if (setsid() == -1) exit(EXIT_FAILURE); // 二次 fork 後孫進程再也不是會話組首進程, 於是孫進程沒法從新打開一個新的控制終端 // 執行成功後 Process ID(PID) != Process Group ID(PGID) == Session ID(SID) switch (fork()) { case -1: exit(EXIT_FAILURE); case 0: break; default: exit(EXIT_SUCCESS); } // 子進程設置新的工做目錄是 根目錄 "/", 避免存在掛載磁盤一直被佔用的狀況 if (chdir("/")) {} // 子進程重置 建立文件 權限 umask(0); // 相關句柄善後, 節省資源 fflush(stderr); fflush(stdout); for (int fd = sysconf(_SC_OPEN_MAX); fd >= 0; fd--) close(fd); }
歡迎交流指正 ~
感恩❉ 不忘初心, 與善者同行 ❤