首页 技术 正文
技术 2022年11月21日
0 收藏 315 点赞 3,770 浏览 999 个字

嵌入式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)

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,075
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,551
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,399
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,811
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,893