Jump to content

daemon in C/C++

- - - - -

  • Please log in to reply
1 reply to this topic

#1
psepheroth

psepheroth

    Learning Programmer

  • Members
  • PipPipPip
  • 31 posts
Hello all,
I was about to create a c++ daemon. But I don't know what's the best way to do this.
I was thinking:
while (true)

{

/*

 keep on listening

 etc...

*/

sleep (1);

}

I know this is kinda lame/amateur.
Any ideas what's the best way to create a C/C++ daemon?

#2
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
Depends on what you want your daemon to do. If you need an event loop, then what you listed above could certainly work. (Although I would personally use a boolean variable called 'alive' as the condition for the while loop rather than a hard-coded value. That way, some other process can gracefully terminate the daemon simply by setting that value to false.) Choosing to sleep inside this loop could have negative consequences, especially if the nature of your program requires it to respond quickly to input. Again, it depends on what you want your daemon to do.

Another important element to writing a daemon is to fork off from the main process, then exit the main process, leaving the child running in the background. That way, you can invoke your daemon from the command line and immediately be returned to the command shell for doing other tasks, while your daemon continues to run [transparently] in the background.

I googled real quick and found this information which might prove helpful to you:
Linux Daemon Writing HOWTO
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users