嵌入式Linux應用程式開發詳解------(建立守護進程)

來源:互聯網
上載者:User

標籤:des   style   http   io   os   使用   ar   for   檔案   

嵌入式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. }





來自為知筆記(Wiz)

嵌入式Linux應用程式開發詳解------(建立守護進程)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.