First, Introduction
Sometimes the work may write some of these programs, which run as a background process, the life cycle is longer than the normal process, it runs when the system is powered on, until it is forced to shut down or the system shuts down. It's an elf process or daemon.--daemon process
Ii. steps to write the wizard process
1. Creating a child process, exiting the parent process
2. Change the file's mask
3. Open the log file to write the execution information to it
4. Create a unique session ID (SID)
5. Change the current work path to a safe place
6. Turn off standard file descriptors
7. Write the actual sprite process code
Third, examples
/******************************************************************************** File name:daemon.cpp* Author : zjw* Email: [Email protected]* Create time:2015 January 05 Monday 16:00 15 seconds **************************** ***************************************************/#include<unistd.h>#include<sys/stat.h>#include<sys/types.h>#include<time.h>#include<stdlib.h>#include<iostream>#include<fstream>using namespacestd;intMainintargcChar**argv) {pid_t pid, sid; //Fork off the parent processPID =Fork (); if(PID <0) {exit (-1); } //If We got a good PID, then we can exit the parent process. if(PID >0) {exit (-1); } //Change the file mode maskUmask0); //Open any logs hereOfstream Fout ("/var/log/daemon.log"); if(!fout) {Exit (-1); } //Create a new SID (Session ID) for the child processSid =Setsid (); if(Sid <0) { //Log any failureExit (-1); } //The current working directory if((ChDir ("/")) <0) { //Log any failureExit (-1); } //Close out of the standard file descriptorsClose (Stdin_fileno); Close (Stdout_fileno); Close (Stderr_fileno); //daemon-specific initialization goes here//The big Loop while(true) {time_t timenow; Time (&TimeNow); Fout<< asctime (localtime (&timenow)) <<Endl; Sleep ( -); } cout<<" Over"<<Endl; return 0;}
This is just a simple instance code that simply describes the general steps of writing the sprite process. Where I encountered a problem with the runtime error, debug trace found unable to open file/var/log/daemon.log, obviously a problem with permissions. Run with the root user, OK. Here's another question: How do I debug a fork's subprocess? Workaround: Google gdb multi-process.
Linux Wizard Process