Daemon in C++

Steps for daemon.

  1. fork child process.
  2. if child fork success, exit parent.
  3. umask file permission for child.
  4. set session id or attach with init process.
  5. change current working dirctory.
  6. close standard file descriptors.
  7. start daemon work initilization.
  8. run daemon loop.
  9. handle signals for terminating( we will see next blog).
Sample code daemon loop used Posix Queue toen-queuemessages from old post.
Sample code

void run_daemon() { fork_child(); initchild(); run_daemon(); exit(EXIT_SUCCESS); }

Function used in sample

void fork_child() { pid_t sid;
// fork off the parent process
pid = fork();
// return -1 if failed
if (pid < 0) { exit(EXIT_FAILURE); }
// If we got PID, then exit the parent process.
if (pid > 0) { exit(EXIT_SUCCESS); } } void initchild() { pid_t sid
// set the file mask.
umask(0);
// open log file here for logging.
// set session id for child process.
sid = setsid(); if (sid < 0) { exit(EXIT_FAILURE); }
// change the current working directory
if ((chdir("/")) < 0) { exit(EXIT_FAILURE); }
// close standard file descriptors
close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); }

Main daemon loop

void daemon_loop() {
// daemon-specific initialization
mqd_t mqid; if(open_queue(mqid)){
// daemon loop
while (1) {
// daemon work
send_message(mqid,"This message from daemon",64); sleep(1); // wait } close_queue(mqid); } }

No comments:

Post a Comment

would you like it. :)