How to Daemonize in Linux
2012-08-02 00:04
447 查看
转自http://www.itp.uzh.ch/~dpotter/howto/daemonize
简单易懂的daemonize实现代码:
简单易懂的daemonize实现代码:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 static void daemonize(void) { pid_t pid, sid; /* already a daemon */ if (getppid() == 1) { return; } /* Fork off the parent process */ pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { exit(EXIT_SUCCESS); } /* At this point we are executing as the child process */ /* Change the file mode mask */ umask(0); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { exit(EXIT_FAILURE); } /* Change the current working directory. This prevents the current * directory from being locked; hence not being able to remove it. */ if ((chdir("/")) < 0) { exit(EXIT_FAILURE); } /* Redirect standard files to /dev/null */ freopen("/dev/null", "r", stdin); freopen("/dev/null", "w", stdout); freopen("/dev/null", "w", stderr); } int main(int argc, char **argv) { daemonize(); /* Now we are a daemon -- do the work for which we were paid */ while (1) { sleep(1); } return 0; }
相关文章推荐
- How to Daemonize in Linux
- How to Daemonize in Linux
- How to write a Daemon process in Linux
- How to uninstall/update/ your python in Linux
- How to reboot MySQL in Linux
- How to reimplement (or wrap) a syscall function in linux?
- How to use windows fonts in Linux WPS (kingsoft-office)
- How to count the number of threads in a process on Linux
- How to change I/O scheduler in Linux
- linux 机器之间 zssh, rz, sz互相传输 ( How to install zssh in Ubuntu 13.10 (Saucy))
- How To Set Up Port Forwarding in Linux
- Linux Daemon Writing HOWTO
- How to install Eclipse in linux
- Linux: How to enable root user in Gnome for VirtualBox Fedora?
- How to install multi OS(Windows/Linux) in one PC box and boot them easily
- How to sleep in the Linux kernel?
- how to search new file in linux
- How to read Mac .DMG file in Linux or PC
- 【Linux】How to Uninstall a Program in Linux(如何卸载Linux系统的应用程序)
- How to Install VM Tools for Linux Platform in VMware Workstation