Server program daemon and the code of the daemon process

Source: Internet
Author: User

The general server program is running in the background process (daemon), so how to make the server process daemon?

Here are the steps you follow to write the daemon:

1. Create a child process, close the parent process, 2. Sets the file permission mask. When a process creates a new file (using the open (const char *pathname, int flags, mode_t mode) system call, the file's permissions will be mode&0777;

3. Create a new session, set the process as the leader of the process group;

4. Switch the working directory;

5. Turn off standard input devices, standard output devices, and standard error output devices;

6. Close other file descriptors that are already open;

7. REDIRECT standard input, standard output, standard error to/dev/null file

Here is an example:

BOOLdaemonize () {pid_t PID=Fork (); if(PID <0 )    {        return false; }    Else if(PID >0) {exit (0 ); } umask (0 ); pid_t Sid=Setsid (); if(Sid <0 )    {        return false; }    if((ChDir ("/")) <0 )    {        /*Log the failure*/        return false;    } close (Stdin_fileno);    Close (Stdout_fileno);    Close (Stderr_fileno); Open ("/dev/null", o_rdonly); Open ("/dev/null", O_RDWR); Open ("/dev/null", O_RDWR); return true;}

In fact, Linux provides library functions that perform the same functions:

#include <unistd.h>int daemon (intint noclose);

Where the Nochdir parameter is used to determine whether to change the working directory, if Nochdir = 0, the working directory will be set to the root directory (/), otherwise continue to use the current working directory.

Noclose = 0 o'clock, standard input, standard output, standard error are redirected to the/dev/null file, otherwise the original device is still used.

Successful return 0, failure return-1

Server program daemon and the code of the daemon 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.