简体   繁体   中英

Daemon Socket server in C

I have successfully created a C program which runs an infinite loop waiting for a connecting through sockets. I would like to make it a daemon and be able to start and stop it. How can I do it? What changes should I do to my code to run in the background?

The classic tasks required to become a daemon are:

  1. Change the working directory to the root, so that your daemon does not pin another mount;
  2. Call fork() and have the parent exit, so that the process is not a process group leader;
  3. Redirect standard input, standard output and standard error to /dev/null ;
  4. Call setsid() to make the process a session group leader of a new session with no controlling terminal.

Without error-checking:

chdir("/);

if (fork() > 0)
    _exit();

close(0);
close(1);
close(2);
open("/dev/null", O_RDWR);
dup(0);
dup(0);

setsid();

On Linux, glibc provides a daemon() helper function to do these tasks.

To run ac program as daemon you need to do the following steps.

// Create child process
process_id = fork();

//unmask the file mode
umask(0);

//change the directory as your home directory
strcpy(home,"HOME");                                                                                   
home=getenv(home);
chdir(home) ;


//set new session
sid = setsid();
close(STDIN_FILENO); open("/dev/null", O_RDWR);
close(STDOUT_FILENO); open("/dev/null", O_RDWR); 
close(STDERR_FILENO); open("/dev/null", O_RDWR);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM