- /*------------- daemon.c -----------*/
- /*
- 说明:让程序自动在后台运行
-
- cc -o daemon daemon.c
- */
- #include <fcntl.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <stdbool.h>
- int daemon(int nochdir, int noclose);
- int main(int argc, char** argv)
- {
- int c;
- bool daemonize = false;
- int maxcore = 0;
- int verbose = 0;
-
- /* set stderr non-buffering (for running under, say, daemontools) */
- setbuf(stderr, NULL);
-
- /* process arguments */
- while ((c = getopt(argc, argv, "dc:v")) != -1) {
- switch (c) {
- case 'd':
- daemonize = true;
- break;
- case 'c':
- maxcore = atoi(optarg);
- break;
- case 'v':
- verbose = 1;
- break;
- default:
- fprintf(stderr, "Illegal argument \"%c\"\n", c);
- return 1;
- }
- }
-
- /* daemonize if requested */
- /* if we want to ensure our ability to dump core, don't chdir to / */
- if (daemonize) {
- int res;
- res = daemon(maxcore, verbose);
- if (res == -1) {
- fprintf(stderr, "failed to daemon() in order to daemonize\n");
- return 1;
- }
- }
-
- int i = 100;
- while(i--)
- {
- sleep(2);
- fprintf(stdout,"%d ......\n", i);
- }
-
- return 0;
- }
- int daemon(int nochdir, int noclose)
- {
- int fd;
- switch (fork()) {
- case -1:
- return (-1);
- case 0:
- break;
- default:
- _exit(EXIT_SUCCESS);
- }
- if (setsid() == -1)
- return (-1);
- if (nochdir == 0) {
- if(chdir("/") != 0) {
- perror("chdir");
- return (-1);
- }
- }
- if (noclose == 0 && (fd = open("/dev/null", O_RDWR, 0)) != -1) {
- if(dup2(fd, STDIN_FILENO) < 0) {
- perror("dup2 stdin");
- return (-1);
- }
- if(dup2(fd, STDOUT_FILENO) < 0) {
- perror("dup2 stdout");
- return (-1);
- }
- if(dup2(fd, STDERR_FILENO) < 0) {
- perror("dup2 stderr");
- return (-1);
- }
- if (fd > STDERR_FILENO) {
- if(close(fd) < 0) {
- perror("close");
- return (-1);
- }
- }
- }
- return (0);
- }
阅读(686) | 评论(0) | 转发(0) |