Embedded Linux application Development detailed------(Create daemon)

Source: Internet
Author: User

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:
  
 
  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. }





From for notes (Wiz)

Embedded Linux application Development detailed------(Create daemon)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.