Daemon (Daemon)

Source: Internet
Author: User

Category: C/

Concept: Daemon (Daemon) is a special process running in the background. It is independent of the control terminal and periodically performs some sort of task or waits to handle certain occurrences. Daemons are a very useful process. Most Linux servers are implemented with daemons. For example, the Internet server Inetd,web server httpd and so on. At the same time, the daemon completes many system tasks. For example, the job planning process Crond, the printing process lpd and so on. (at the end of the letter D is the meaning of daemon). Create step: ① causes the process to run in the background to create the child process parent process exit if ((PID = fork ()) >0) exit (0), else if (pid<0) {perror ("fail to for    K "); Exit (-1);} ② out of control terminal, logon session and process group (create new session) it is necessary to introduce the relationship between the process and the control terminal in Linux, the logon session and the process group: the process belongs to a process group, and the process group number (GID) is the process number (PID) of the process leader. A logon session can contain multiple process groups. These process groups share a control terminal. This control terminal is usually the login terminal of the creation process. Control terminals, logon sessions and process groups are usually inherited from the parent process. Our aim is to get rid of them so that they are not affected by them. The method is based on the 1th, call Setsid () to make the process a conversation leader: Setsid ();
Description: The Setsid () call failed when the process was the session leader.   But the 1th has ensured that the process is not a conversation leader. After the Setsid () call succeeds, the process becomes the new session leader and the new process leader, and is detached from the original logon session and process group.   Due to the exclusivity of the session process to the control terminal, the process is disconnected from the control terminal at the same time. ③ Disable process re-opening control terminal Now, the process has become a session leader without terminal. But it can be re-applied to open a control terminal. You can prevent a process from reopening the control terminal by making the process no longer a session leader: if (Pid=fork ())
Exit (0);//End first child process, second child process continue (second child process is no longer session leader) ④ close all file descriptor processes inherit the open file descriptor from the parent process that created it. If not closed, system resources will be wasted, causing the file system where the process resides to be unable to unload and cause unexpected errors: for (I=0;i<=getdtablesize (); i++)Close (i);⑤ the file system in which the working directory resides cannot be removed when the current working directory process activity is changed. It is generally necessary to change the working directory to the root directory. For processes that need to dump the core, the process of writing the log changes the working directory to a specific directory such as/tmp:chdir ("/tmp");⑥ Resetting the permission maskThe process inherits the file creation mask from the parent process that created it. It may modify the access bit of the file created by the daemon. To prevent this, the file creation mask is cleared:umask (0);⑦ processing of SIGCHLD signal processing SIGCHLD signal is not necessary. However, for some processes, in particular, server processes often generate child processes to process requests when requests arrive. If the parent process does not wait for the child process to end, the child process becomes a zombie process (zombie) and thus consumes system resources. If the parent process waits for the child process to end, it increases the burden on the parent process and affects the concurrency performance of the server process. The operation of the SIGCHLD signal can be easily set to Sig_ign under Linux.signal (sigchld,sig_ign);
This way, the kernel does not spawn a zombie process at the end of the child process. Unlike BSD4, the BSD4 must explicitly wait for the child process to end before releasing the zombie process. No Code No Truth code Description: INIT_DEAMON.C: Follow the steps above to create a daemonTEST.c: Call the Create daemon function to print the system time to the Print_time file in the/tmp directory every second
  1. /*name: init_deamon.c
  2. *function: Create a daemon
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <signal.h>
  8. #include <sys/param.h>
  9. #include <sys/types.h>
  10. #include <sys/stat.h>
  11. void Init_deamon (void)
  12. {
  13. int pid;
  14. int i;
  15. /* Process the SIGCHLD signal. Processing SIGCHLD signals is not a must. However, for some processes, in particular, server processes often generate child processes to process requests when requests arrive. If the parent process does not wait for the child process to end, the child process becomes a zombie process (zombie) and thus consumes system resources. */
  16. if (signal (sigchld,sig_ign) = = Sig_err) {
  17. printf ("Cant signal in Init_daemon.");
  18. Exit (1);
  19. }
  20. if (Pid=fork ())
  21. Exit (0);//is parent process, end parent process
  22. else if (pid< 0) {
  23. Perror ("fail to Fork1");
  24. Exit (1);//fork failed, exit
  25. }
  26. Is the first child process, the background continues to execute
  27. Setsid ();//first child process becomes new conversation leader and process leader
  28. and separated from the control terminal
  29. if (Pid=fork ())
  30. Exit (0);//is the first child process, ending the first child process
  31. else if (pid< 0)
  32. Exit (1);//fork failed, Exit
  33. Is the second child process, continue
  34. The second child process is no longer a conversation leader
  35. For (i=0;i< getdtablesize (); ++i)//Close Open File descriptor
  36. Close (i);
  37. ChDir ("/tmp");//Change Working directory to/TMP
  38. Umask (0);//Reset file creation Mask
  39. Return
  40. }
  1. /* Name : test.c
  2. * function : Call the Init_deamon function to turn the process into a daemon, and then print the current time to the Print_time file in the/tmp directory every second
  3. * */
  4. #include <stdio.h>
  5. #include <time.h>
  6. void Init_deamon (void);//daemon initialization function
  7. void Main ()
  8. {
  9. FILE *FP;
  10. time_t T;
  11. Init_deamon ();//Initialize to daemon
  12. while (1)//report running status to Test.log every minute
  13. {
  14. Sleep (1);//Sleeping for one second
  15. if ((Fp=fopen ("Print_time", "a")) >=0)
  16. {
  17. T=time (0);
  18. fprintf (FP, "The Time right now is:%s", Asctime (LocalTime (&t)));
  19. Fclose (FP);
  20. }
  21. }
  22. Return
  23. }
Test: ============2014-4-11 Update ============
Some UNIX variants provide aDaemonC library function to implement this function. Both BSD and Linux provide this daemon function.

    1. #include <unistd.h>
    2. int daemon (int nochdir, int noclose);

Excerpt from: http://blog.chinaunix.net/uid-25365622-id-3055635.html

Daemon (Daemon)

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.