嵌入式Linux应用程序开发详解(创建守护进程)

嵌入式Linux应用程序开发详解
华清远见
本文只是阅读文摘。

创建一个守护进程的步骤:
1、创建一个子进程,然后退出父进程;
2、在子进程中使用创建新会话---setsid();
3、改变当前工作目录---chdir();
4、重新设置文件权限掩码---umask();
5、关闭所有的文件描述符---close(fdx);
6、设置daemon程序的任务---此例主要在while循环中体现。


下面是一个例子程序:

  1. /* daemon
  2. * how to create a daemon process?
  3. * --Just follow these steps.
  4. * 2014-09-28
  5. * zsl
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <sys/types.h>
  10. #include <fcntl.h>
  11. #define MAXFILE 65536
  12. int main()
  13. {
  14. pid_t child_pid, new_pid;
  15. int fd;
  16. int i;
  17. child_pid = fork();
  18. if ( child_pid < 0 ) // fork failed
  19. {
  20. perror("fork");
  21. exit(1);
  22. }
  23. else if (child_pid > 0 ) // parent
  24. {
  25. fprintf(stderr, "Parent exit...\n");
  26. exit(0);
  27. }
  28. else // child
  29. {
  30. /* Create a new session */
  31. new_pid = setsid();
  32. if ( new_pid < 0)
  33. {
  34. perror("setsid");
  35. exit(1);
  36. }
  37. /* Change dir */
  38. if ( chdir("/") != 0 )
  39. {
  40. perror("chdir");
  41. exit(2);
  42. }
  43. /* Set umask */
  44. umask(0000);
  45. /* Close all file descriptor */
  46. for (i = 0; i < MAXFILE; i ++)
  47. {
  48. close(i);
  49. }
  50. /* The daemon job */
  51. while(1)
  52. {
  53. if ((fd = open("/tmp/daemon_log.txt", O_CREAT | O_APPEND | O_WRONLY, 0600)) == -1)
  54. {
  55. perror("open");
  56. exit(3);
  57. }
  58. write(fd, "daemon is working...\n", 21);
  59. close (fd);
  60. sleep(10);
  61. }
  62. } // end of childe process
  63. return 0;
  64. }








原文地址:https://www.cnblogs.com/LinTeX9527/p/3997746.html