#include #include #include #include char debug_mode = 0; void child(){ int logfile_fd; if(!debug_mode){ close(0); close(1); close(2); logfile_fd = open("daemon_log", O_WRONLY | O_CREAT | O_TRUNC, 0644); dup2(logfile_fd, 1); dup2(logfile_fd, 2); } chdir("/"); // Wikipedia points out a lot of daemons do this char cwd[128]; getcwd(cwd, 128); write(1, cwd, strlen(cwd)); while(1){ sleep(1); write(1, "Child is still alive\n", 21); } // Won't run anyway close(logfile_fd); } int main(int argc, char ** argv){ if(argc > 1 && !strcmp(argv[1], "--debug")) debug_mode = 1; if(debug_mode) child(); else { pid_t pid = fork(); if(pid) { // parent process return 0; } else { // child process child(); } } }