Chinaunix首页 | 论坛 | 博客
  • 博客访问: 154643
  • 博文数量: 27
  • 博客积分: 710
  • 博客等级: 上士
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-03 20:08
文章分类

全部博文(27)

文章存档

2012年(1)

2011年(22)

2010年(4)

我的朋友

分类: LINUX

2011-10-06 00:19:11

Daemons are processes that live for a long time.They are often started when the system is bootstrapped and terminate only when the system is shut down,they run in the background.Unix systems have numerous daemons that perform day-to-day activities.
 
 
 
★ Characteristics
 
(1) run with superuser privilege(most of the daemons,a use ID of 0)
(2) without contronlling terminal (terminal name is set to a queston mask,tty=? )
(3) the terminal foreground process group is -1
(4) All the user-level daemons are process group leaders and session leaders and are the only processes in their process group and session.
(5) most of these daemons is the init process
 
★ Coding Rules
(1) call umask to set the file mode creation mask to 0
(2) call fork to create child process and have the parent exit
(3) call setsid to create a new session
(4) change the current directory to the root directory
(5) close the unneeded file descriptors
 
★ Example
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<fcntl.h>
  4. #include<sys/wait.h>
  5. #include<sys/types.h>
  6. #include<unistd.h>
  7. #include<sys/resource.h>

  8. int main()
  9. {
  10.     pid_t pid;
  11.     struct rlimit r1;
  12.     int i;
  13.     
  14.     //clear the file creation mask
  15.     umask(0);
  16.     
  17.     //get maximum number of file descriptors
  18.     if(getrlimit(RLIMIT_NOFILE,&r1) < 0)
  19.         printf("can't get file limit\n");

  20.     pid = fork();
  21.     if(pid < 0)
  22.         printf("fork error\n");
  23.     else if(pid > 0)
  24.         exit(0);

  25.     setsid();
  26.     
  27.     //change directory to root directory
  28.     if(chdir("/") < 0)
  29.         printf("can't change directory\n");
  30.     
  31.     //close all open file descriptors
  32.     if(r1.rlim_max == RLIM_INFINITY)
  33.         r1.rlim_max = 1024;
  34.     for(i = 1;i < r1.rlim_max; i++)
  35.         close(i);
  36. }
 
 
阅读(1038) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~