Steps for daemon.
- fork child process.
- if child fork success, exit parent.
- umask file permission for child.
- set session id or attach with init process.
- change current working dirctory.
- close standard file descriptors.
- start daemon work initilization.
- run daemon loop.
- handle signals for terminating( we will see next blog).
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. :)