Two implementations of Daemons

Source: Internet
Author: User

Directly on the code, refer to the UNIX environment advanced programming

1 voidDaemon ()2 {3     structRlimit RL;4Umask0);5 pid_t pid;6PID =fork ();7     if(PID <0 )8     {9Perror ("Fork Error");Ten         return 0; One     } A     if(PID >0)/*Parent*/ -     { -Exit0); the     } -     Else /* Child*/ -     { -         /* + * Standard input can still be used before closing the descriptor, standard output -          */ + Setsid (); AGetrlimit (rlimit_nofile,&RL); atprintf"The max file num is%d: \ n", Rl.rlim_max);/*Setsid () has been separated from the control terminal*/ -printf"The max file num is%d: \ n", rlim_infinity); -         if(Rl.rlim_max = =rlim_infinity) -Rl.rlim_max =1024x768; -  -         inti; in          for(i=0; i<rl.rlim_max; i++) - Close (i); to         intfd0, Fd1, fd2; +fd0 = open ("/dev/null", O_RDWR); -FD1 = DUP (0); theFD2 = DUP (0); *Openlog ("Hello", Log_cons, Log_daemon); $     }Panax Notoginseng}

Some like to fork on the above basis again, because the above sub-process is the first process of the whole reply, the first process to get a control terminal, daemon can not be connected with the terminal, so fork again, the first child process (the first fork produced by the process) exit, the latest child process ( The second fork-generated process) is not a reply to the first process is not eligible to get back to the control terminal.

Some also handle sighup signals, see Advanced Programming for UNIX environments for SIGHUP signals

The second method:

Direct access to the functions provided by Linux Daemon ()

1 #include <unistd.h>23int  main ()4{5      Daemon (0,0); 6      while (1) {/  * does not end immediately */78    }9 }

Ok...

Two implementations of Daemons

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.