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
- #include<stdio.h>
- #include<stdlib.h>
- #include<fcntl.h>
- #include<sys/wait.h>
- #include<sys/types.h>
- #include<unistd.h>
- #include<sys/resource.h>
- int main()
- {
- pid_t pid;
- struct rlimit r1;
- int i;
-
- //clear the file creation mask
- umask(0);
-
- //get maximum number of file descriptors
- if(getrlimit(RLIMIT_NOFILE,&r1) < 0)
- printf("can't get file limit\n");
- pid = fork();
- if(pid < 0)
- printf("fork error\n");
- else if(pid > 0)
- exit(0);
- setsid();
-
- //change directory to root directory
- if(chdir("/") < 0)
- printf("can't change directory\n");
-
- //close all open file descriptors
- if(r1.rlim_max == RLIM_INFINITY)
- r1.rlim_max = 1024;
- for(i = 1;i < r1.rlim_max; i++)
- close(i);
- }
阅读(1051) | 评论(0) | 转发(0) |