The difference between the Deamon process creation of Linux and its process Exit,_exit,return

Source: Internet
Author: User
Tags session id strcmp

The Dameon process is also called the Daemon, in general he has the following 2 characteristics :
1. The life cycle is very long, once started, generally will not terminate, until the system is launched, but the Dameon process can be stopped or send a signal to kill it 2. In the background, not with any control terminal, terminal signal such as: SIGINT,SIGQUIT,SIGTSTP, And shutting down the terminal will not affect Deamon How to write the daemon process, you need to follow the following rules: (1) executes the fork () function, the parent process exits, and the child process continues this step for two reasons: • The parent process may be the leader of the process group (in the case of a command line launch), thus not able to execute the SETSID function to be executed later, the child process inherits the process group ID of the parent process. and has its own process ID, must not be the leader of the process group, so the child process must be executed later to execute the SETSID function. • If the daemon is started from the terminal command line, the parent process exit is detected by the shell, and the shell displays the shell prompt. Let the child process execute in the background. (2) The child process performs the following three steps to get rid of the relationship with the Environment 1) modify the current directory of the process to be the root directory (/). This is done for a reason because daemon is running and cannot be uninstalled if the current working path contains a file system other than the root file system. As a result, it is common to switch the current working directory to the root directory, or another directory, as long as you ensure that the file system in which the directory resides is not unloaded. chdir("/") 
2) Call the Setsid function. The purpose of this function is to cut off all relationships with the control terminal and create a new session. This step is critical because this step ensures that the child process no longer belongs to the session associated with the control terminal. Therefore, regardless of whether the terminal sends a SIGINT, sigquit, or SIGTSTP signal, or whether the terminal is disconnected, it is independent of the daemon process to be created and does not affect the continuation of the daemon process. 3) Set the file mode creation mask to 0.
 
   
  
  1. umask(0)
This is to allow the file permission property created by the daemon process to be detached from the shell, because by default, the umask of the process originates from the umask of the parent process shell. If Umask (0) is not executed, Then the umask of the parent process shell will affect the umask of the daemon process. If the user changes the umask of the shell, then Dameon umask is changed, Will cause the daemon process to execute every umask information may be inconsistent (3) fork again, the parent process exits, the child process continues
After performing the first two steps, it can be said that it is more complete: a new session, the process is the beginning of the session, and also the first process group process. Process ID, process group ID, and session ID, the values of the three are the same, and the process and terminal are not associated. So why do we have to do the fork function again? The reason is that the daemon process may open an end device, that is, the daemon process may execute code similar to the following as needed:
 
   
  
  1. int fd = open("/dev/console", O_RDWR);
Whether this open end device will become the control terminal of the daemon process depends on two points: the daemon process is not the first process of the session. • System implementation. (BSD-style implementations do not become control terminals for the daemon process, but the POSIX standard says this is determined by the implementation). In this case, to ensure foolproof, only ensure that the daemon process is not the first process of the session, to ensure that the open end device does not automatically become the control terminal. Therefore, after the second fork,fork has to be executed, the parent process exits and the child process continues. At this point, the child process is no longer the first process of the session, nor is it the first process of the process group. (4) Turn off standard input (stdin), standard output (stdout), and standard error (STDERR) because file descriptors 0, 1, and 2 point to the control terminal. The daemon process is no longer associated with any control terminal, so none of these three are meaningful. In general, after shutting down,/dev/null is opened and the DUP2 function is executed to redirect 0, 1, and 2 to/dev/null. This redirection makes sense, preventing subsequent programs from performing I/O library functions on file descriptors 0, 1, and 2, resulting in an error. At this point, the creation of the daemon process is complete, and the process can begin its own real work. The above steps are cumbersome, for C language, GLIBC provides the daemon function, which helps us to transform the program into a daemon process.
 
   
  
  1. #include <unistd.h>
  2. int daemon(int nochdir, int noclose);
The function has two parameters to control one behavior, as follows. One of the NochdirTo control whether the current working directory is switched to the root directory. • 0: Switch the current working directory to/. • 1: Keep the current working directory intact. and NocloseTo control whether standard input, standard output, and standard error are redirected to/dev/null. • 0: Redirect standard input, standard output, and standard error to/dev/null. 1: Keep standard input, standard output, and standard error unchanged. In general, these two entry parameters are 0.
 
   
  
  1. ret = daemon(0,0)
On success, the daemon function returns 0, and on failure, returns-1, and errno. Because the fork function and the SETSID function are called inside the daemon function, errno can see the error condition of the fork function and the SETSID function when an error occurs. GLIBC's daemon function does the same thing as the previous discussion, but does not do it thoroughly and does not perform a second fork.

termination of the processThere are 5 ways to exit a process without regard to threads. NormalThere are 3 types of exits: • Return from main function • Call exit call _exit ExceptionThere are two types of exits: • Call abort to receive a signal terminated by the signal

The interface of the _EXIT function is defined as follows:
 
   
  
  1. #include <unistd.h>
  2. void _exit(int status);
The user calls the _exit function, essentially calling the Exit_group system call. This point has been described in detail in the previous, here will not repeat.
The Exit function is more common in the Exit function, and its interface is defined as follows:
 
   
  
  1. #include <stdlib.h>
  2. void exit(int status);
The _exit () function is also called at the end of the exit () function, but exit does other work before calling _exit: 1) Executes the cleanup function defined by the user by invoking the Atexit function or On_exit. 2) Close all open streams (stream), all buffered data is written (flush), and temporary files created by Tmpfile will be deleted. 3) Call _exit. Figure 4-11 shows the difference between the Exit function and the _exit function.
The following describes the difference between the Exit function and the _exit function. First, the Exit function executes the cleanup function that is registered by the user. The user can define the cleanup function by calling the Atexit () function or the On_exit () function. These cleanup functions are executed when calling return or calling exit. The execution order is reversed from the order in which the function is registered. When a process receives a fatal signal and exits, the registered cleanup function is not executed, and when the process calls _exit exits, the registered cleanup function is not executed, and when a cleanup function is executed, the cleanup function does not return if a fatal signal is received or the cleanup function calls the _exit () function. This causes the cleanup functions that are to be executed at the back of the queue to be discarded. The Exit function is followed by flushing (flush) The buffer of the standard I/O library and closing the stream. Many I/O-related functions provided by glibc provide buffers for caching large chunks of data. There are three ways to buffer: unbuffered (_IONBF), row buffer (_IOLBF), and full buffering (_IOFBF). • No buffering: There is no buffer, and every call to the Stdio library function calls the Read/write system call immediately. • Row buffering: For the output stream, before the newline character is received, Buffers the data unless the buffer is full. For an input stream, reads one row of data at a time. • Full buffering: The Read/write system call is not invoked to read and write until the buffer is full. For the latter two buffers, this can happen: when the process exits, there may be no flush data in the buffer. If you do not flush the buffer, the data for the buffer is lost. For example, the row buffer does not wait for a newline character, or the full buffer does not wait until the buffer is full. In particular the latter, it is easy to appear because the glibc buffer default is 8192 bytes. The exit function flushes the buffer's data before closing the stream, ensuring that the data in the buffer is not lost.
  
 
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. void foo()
  5. {
  6. fprintf(stderr,"foo says bye.\n");
  7. }
  8. void bar()
  9. {
  10. fprintf(stderr,"bar says bye.\n");
  11. }
  12. int main(int argc, char **argv)
  13. {
  14. atexit(foo);
  15. atexit(bar);
  16. fprintf(stdout,"Oops ... forgot a newline!");
  17. sleep(2);
  18. if (argc > 1 && strcmp(argv[1],"exit") == 0)
  19. exit(0);
  20. if (argc > 1 && strcmp(argv[1],"_exit") == 0)
  21. _exit(0);

  22.     return 0;
  23. }
Note that the above example code, the fprintf printed string is not a newline character, for the standard output stream stdout, the use of a row buffer, before the line feed is received will not have output. The output is as follows:
  
 
  1. [email protected]-hacks:exit$ ./test exit //调用exit结束,输出了缓冲区的字符
  2. bar says bye.
  3. foo says bye.
  4. Oops ... forgot a newline![email protected]-hacks:exit$ //调用return 输出了缓冲区字符
  5. [email protected]-hacks:exit$
  6. [email protected]-hacks:exit$ ./test
  7. bar says bye.
  8. foo says bye.
  9. Oops ... forgot a newline![email protected]-hacks:exit$ //直接调用_exit没有输出缓冲区的字符
  10. [email protected]-hacks:exit$
  11. [email protected]-hacks:exit$ ./test _exit
  12. [email protected]-hacks:~/code/self/c/exit$
Although the data in the buffer does not wait for a newline character, the data in the buffer will be flushed, either by calling return or calling exit, "Oops...forgot a newline! "will be output. Because the exit () function is responsible for this. As can be seen from the output of the test code, the exit () function first executes the user-registered cleanup function before the buffer flushing is performed.
Third, there is a temporary file, and the Exit function is responsible for deleting the temporary file.The Exit Function finally calls the _exit () function, which eventually goes to the kernel cleanup.

return exitReturn is a more common method of terminating a process. Executing return (n) is equivalent to executing exit (n) because the run-time function that calls main () treats the return value of main as an argument to exit.








From for notes (Wiz)

The difference between the Deamon process creation of Linux and its process Exit,_exit,return

Related Article

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.