Embedded Linux application Development detailed Jie Huaqing Vision This article is just reading the digest.
Steps to create a daemon: 1, create a child process, and then exit the parent process, 2, create a new session in a child process---setsid (), 3, change the current working directory---chdir (), 4, reset the file permission mask---umask (), 5, Close all file descriptors---close (FDX), 6, set the task of the daemon program---This example is mainly reflected in the while loop.
Here is an example program:
/* daemon
* how to create a daemon process?
* --Just follow these steps.
* 2014-09-28
* zsl
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#define MAXFILE 65536
int main()
{
pid_t child_pid, new_pid;
int fd;
int i;
child_pid = fork();
if ( child_pid < 0 ) // fork failed
{
perror("fork");
exit(1);
}
else if (child_pid > 0 ) // parent
{
fprintf(stderr, "Parent exit...\n");
exit(0);
}
else // child
{
/* Create a new session */
new_pid = setsid();
if ( new_pid < 0)
{
perror("setsid");
exit(1);
}
/* Change dir */
if ( chdir("/") != 0 )
{
perror("chdir");
exit(2);
}
/* Set umask */
umask(0000);
/* Close all file descriptor */
for (i = 0; i < MAXFILE; i ++)
{
close(i);
}
/* The daemon job */
while(1)
{
if ((fd = open("/tmp/daemon_log.txt", O_CREAT | O_APPEND | O_WRONLY, 0600)) == -1)
{
perror("open");
exit(3);
}
write(fd, "daemon is working...\n", 21);
close (fd);
sleep(10);
}
} // end of childe process
return 0;
}
From for notes (Wiz)
Embedded Linux application Development detailed------(Create daemon)