user2480729
user2480729

Reputation: 3

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?

Upvotes: 0

Views: 2755

Answers (2)

reegan vijay
reegan vijay

Reputation: 161

To run a c 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);

Upvotes: 1

caf
caf

Reputation: 239341

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.

Upvotes: 2

Related Questions