嵌入式Linux应用程序开发详解------(创建守护进程)
/* 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;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。