Programming Tips - How can my program background itself?

Date: 2012apr8 OS: Linux Warning: Now you'd probably use systemd Q. How can my program background itself? A. In your program's main() call the function daemonize() that is listed here. It does all kinds of good stuff. But mostly it forks itself; the parent exits and the child continues.
// helper function void signal_handler(int signum) { log("Get signum=%x\n",signum); player_progress_exit(); signal(signum, SIG_DFL); raise(signum); } void daemonize() { pid_t pid, sid; if (getppid() == 1) return; pid = fork(); if (pid < 0) { log("daemonize failed on fork"); exit(0); } if (pid > 0) exit(0); sid = setsid(); if (sid < 0) exit(-1); umask(0); if ((chdir("/")) < 0) exit(0); signal(SIGCHLD, SIG_IGN); signal(SIGTSTP, SIG_IGN); signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGHUP, signal_handler); signal(SIGTERM, signal_handler); signal(SIGSEGV, signal_handler); }
I don't know what the license of this code is. But I have seen it (or variations) in many daemons.