In the past, when we were reading "Advanced Programming in UNIX environments", we had a special whole chapter detailing how to compile a background daemon program (genie Program), mainly involving creating session groups, switch to the working directory, set file blocking, and disable unnecessary descriptor operations. These operations are similar for every background program.
In Linux, a function is provided to complete the daemon process. The prototype of this function is as follows:
int daemon (int __nochdir, int __noclose);
If the value of _ nochdir is 0, the working directory is switched to the root directory. If _ noclose is 0, the standard input is made, both output and standard errors are redirected to/dev/null.
After this function is called, the program runs in the background and becomes a daemon program. Most services in Linux run in this way.
Let's look at a simple example. For example, compile the example program test. C.
#include <unistd.h>#include <stdio.h> int do_sth(){ //Add what u want
printf("hello/n"); return 0;}int main(){ daemon(0,0); while ( 1 ) { do_sth(); sleep(1); }}
Compile and run:
whc@ubuntu:~/test$ gcc -Wall test.c -o www
whc@ubuntu:~/test$ ./www
The program enters the background and displays the Process status through PS. the ID of the parent process of the process is 1, that is, the INIT process.
whc@ubuntu:~/test$ ps -elf | grep www
5 S www-data 20173 6295 0 80 0 - 6038 - 05:04 ? 00:00:00 /usr/sbin/apache2 -k start
1 S whc 26721 1 0 80 0 - 390 - 10:14 ? 00:00:00 ./www
0 R whc 26752 26657 0 80 0 - 805 - 10:15 pts/4 00:00:00 grep www
Use lsof to view the files opened by the WWW process. The file descriptors 0, 1, and 2 are redirected to/dev/null.
WHC @ Ubuntu :~ /Test $/usr/bin/lsof-P 26721
Command PID user FD type device size node name
WWW 26721 whc cwd dir 8, 1 4096 2/
WWW 26721 whc rtd dir 8, 1 4096 2/
WWW 26721 whc txt Reg 6491 101021/home/WHC/wei1__work/daemon/WWW
WWW 26721 WHC mem Reg 1364388 458293/lib/tls/i686/cmov/libc-2.7.so
WWW 26721 WHC mem Reg 109152 432499/lib/ld-2.7.so
WWW 26721 WHC 0u CHR 6448/dev/null
WWW 26721 WHC 1u CHR 6448/dev/null
WWW 26721 WHC 2u CHR 6448/dev/null
The current working directory (CWD) of the process is the root directory '/', the daemon function has helped us complete the daemon process. Next we only need to pay attention to the implementation of program functions.