Linux Daemon Process creation process

Source: Internet
Author: User

#include <sys/stat.h>#include<fcntl.h>/*bit-mask values for ' flags ' argument of Becomedaemon ()*/#defineBd_no_chdir * */Don ' t CHDIR ("/") */#defineBd_no_close_files/* Don ' t CLOSE all open FILES */#defineBd_no_reopen_std_fds/* Don ' t REOPEN stdin, stdout, andstderr to/dev/NULL*/#defineBd_no_umask0 010/* Don ' t do a umask (0) */#defineBd_max_close 8192/* Maximum file descriptors to CLOSE ifsysconf (_sc_open_max) isIndeterminate * *intBecomedaemon (intFlags/*Returns 0 On success, 1 on Error*/{    intMaxfd, FD; Switch(Fork ())/*Become background Process*/    {                       Case-1:return-1;  Case 0: Break;/*Child falls through ...*/    default: _exit (exit_success);/*While parent terminates*/    }    if(Setsid () = =-1)/*become leader of new session*/        return-1; Switch(Fork ()) {/*ensure we is not session leader*/     Case-1:return-1;  Case 0: Break; default: _exit (exit_success); }    if(! (Flags &bd_no_umask0)) Umask (0);/*Clear file Mode creation Mask*/    if(! (Flags &Bd_no_chdir)) ChDir ("/");/*Change to root directory*/    if(! (Flags & Bd_no_close_files)) {/*Close all open files*/maxfd=sysconf (_sc_open_max); if(Maxfd = =-1)/*Limit is indeterminate ...*/maxfd= Bd_max_close;/*So take a guess*/         for(FD =0; FD < MAXFD; fd++) Close (FD); }    if(! (Flags &Bd_no_reopen_std_fds))            {Close (Stdin_fileno); /*Reopen Standard FD ' s to/dev/null*/FD= Open ("/dev/null", O_RDWR); if(FD! = Stdin_fileno)/*' fd ' should be 0*/            return-1; if(Dup2 (Stdin_fileno, stdout_fileno)! =Stdout_fileno)return-1; if(Dup2 (Stdin_fileno, stderr_fileno)! =Stderr_fileno)return-1; }    return 0;}

Linux Daemon Process creation process

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.