Golang Creating a daemon Program

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. # # # Daemon's concept daemon (daemon) is a process that runs in the background, does not control the terminal and cannot interact with the foreground user. A session session (shell) is created when we open a terminal, from the time the user logs on to the end of the user's exit, during which the process executed at that terminal is part of this conversation. A session typically consists of a foreground process group, a background process group, and a session first process (shell program itself). For example, start a 5 process with the following command:> $ proc1 | PROC2 &> $ proc3 | proc4 | Proc5> Proc1 and proc2 belong to the same background process group, PROC3, proc4, and proc5 belong to the same foreground process group, and the shell process itself belongs to a separate process group. The control terminals of these process groups are the same, and they belong to the same session. > * * The essential difference between "background task" and "foreground task" is only one: whether to inherit standard input. Background tasks no longer inherit the current session's standard input (stdin), you cannot enter instructions to the background task, but the background task inherits all the output from standard output (STDOUT) and standard error (STDERR) Background tasks will still be displayed synchronously on the command line * * The Hang-up signal (SIGHUP) is sent to the terminal control process (session-first process, shell process) when the terminal shuts down or detects a disconnected network connection. If the session first process receives the SIGHUP signal, it terminates, and the foreground process group is sent a sighup signal (the process receives the SIGHUP signal default processing is exit), the shell's **huponexit** parameter ' (shopt | grep huponexit) ' Determines whether the shell sends a sighup signal to the background process group when it exits. # # # How to implement a daemon daemon is isolated from the running environment of the parent process that started it (typically the shell program), and the content that needs to be processed roughly includes sessions, control terminals, process groups, file descriptors, file permission masks, working directories, and so on. ' void Init_daemon () {pid_t pid; int i = 0;//1. The child process is created, the parent process exits, and the parent process exits the child process into an orphan process, and the orphan process is adopted by the INIT process (PID 1) if (PID = fork ()) = = 1) {printf ("Fork error!\n"); Exit (1); } if (pid! = 0) {exit (0); The parent process exits}//2. The child process calls **setsid** to create a new session, becomes the conversation's first process, and the child process becomes the leader of the group of processes, and the new session is removed from the control terminal. (The leader process calls Setsid error, so the first step to fork out the sub-process, fork out of the child process will not be the leader process) Setsid (); 3. The child process becomes a non-terminal session-first process, but it can still reapply to open a control terminal. You can end the current process by creating a child process again, so that the process is no longer the session first process to prevent the process from reopening the control terminal. if (PID = fork ()) = =-1) {printf ("Fork error!\n"); Exit (-1); } if (pid! = 0) {exit (0); }//4. Change the current directory to the root directory, reset the file permission mask, close the file descriptor//Because these things are inherited from the parent process chdir ("/tmp"); Change the working directory Umask (0); Resets the file mask for (; I < getdtablesize (); ++i) {Close (i); Close open File descriptor} return; ' # #go语言如何实现守护进程目前Go程序还不能完全实现daemon, because the Go Program runtime may create multiple threads at startup (for memory management, garbage collection, goroutine management, etc.), and fork and multithreaded environments do not coexist harmoniously. [Godaemon] (Https://github.com/VividCortex/godaemon) provides a solution (certainly not a perfect daemon) code example: "Func main () {Godaemon. Makedaemon (&godaemon. daemonattr{})} ' 1. REDIRECT stdin, stdout, stderr to/dev/null, call OS. The startprocess () function starts itself again (exec executes immediately after the fork is finished), setting Setsid to make the newly opened child process a session leader process, and out of control of the terminal, the parent process exits. 2. The child process calls Startproc againESS () Create grandson process (this process is primarily to make the grandson process no longer the session first process to prohibit the process from reopening the control terminal) 3. The grandson process is the final daemon, then changes the current directory to the root directory, resets the file permission mask, and so on. > + * * program will start repeatedly, in Godaemon. The statement before the Makedaemon () function executes multiple times **+ * * by setting Environment variables __daemon_stage program can know what stage they are in **## use Supervisord why bother, just use supervisor!## References [Implementation of the Linux Daemon] (http://alfred-sun.github.io/blog/2015/06/18/daemon-implementation/) [Why the daemon process Fork two times] ( http://wanghaibo.m.blog.chinaunix.net/uid-27105712-id-3356916.html) [Godaemon] (Https://github.com/VividCortex/godaemon)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.