CS162B: Daemonization Jacob T.Chan
Foreground Process Has input/output capabilities These require users at the terminal Lives as long as the terminal that started it Associated with the caller (user or process executing it) or a controlling terminal
Background Process Runs by itself Responding to events aside from I/O Example: SSH (Secure Shell) connection requests Spawned by system upon boot up Has same access privileges as root Usually handles hardare Can be associated with caller, but not under direct control Lack of controlling terminal Termination of parent process
Daemons Background process in Unix These do not die usually or will require restarting They spawn other processes to handle further events Example: upon receiving connection request, server daemon will spawn another process to establish a MORE SPECIFIC connection They write to a certain system log file (found in /var/log) instead of console Reason: they lack controlling terminals
Daemons #include if(fork() != 0) exit(0); // only the child process gets this far – daemonize now! setsid(); // make this process a leader of its own session chdir("/"); // prevents process from hogging a directory // the chdir call prevents "directory in use" issue
Daemons // files created must have rwx permissions for the owner of this process (usually root)and rx permissions for the group umask(027); //remember this? // close stdin, stdout, stderr (where applicable) close(0); // stdin close(1); // stdout close(2); // stderr
Printing out System Logs #include openlog("Daemon Log Test", LOG_PID | LOG_CONS, LOG_USER); Configure system log so that: 1)Whenever this process writes to it, the string "Daemon Log Test" is appended at the beginning. 2)The process ID is logged with every message ( LOG_PID ) and the messages will be written to the console if the system log is unavailable ( LOG_CONS ). 3)Messages are assumed to be generated from an arbitrary process ( LOG_USER ).
Printing out System Logs generate a system log message "AIEEEEE" that will be marked as an error message generated by an arbitrary process syslog(LOG_ERR | LOG_USER, "AIEEEEE"); syslog acts like printf ! remember: it (usually) writes to /var/log int i = 5 + 5; syslog(LOG_ERR | LOG_USER, "5+5=%d", i); closelog(); close file descriptors that were opened to gain access to the system logs by both openlog and syslog (in short, so that it is accessible)