先上代码: getopt函数获取参数  -d 控制台控制运行  -D 后天运行  -h 调用show_help函数。 

编译命令 

gcc -g -W test.c -o test 

注意后台运行 ./test -D  工作目录被切换到了 目录 / 

 1 #include <stdio.h>
 2 #include <sys/socket.h>
 3 #include <sys/types.h>
 4 #include <netinet/in.h>
 5 #include <arpa/inet.h>
 6 #include <unistd.h>
 7 #include <ctype.h>
 8 #include <strings.h>
 9 #include <string.h>
10 #include <sys/stat.h>
11 #include <pthread.h>
12 #include <sys/wait.h>
13 #include <stdlib.h>
14 #include <stdint.h>
15 
16 // gcc -g -W test.c -o test
17 
18 void daemonize(void) {
19     signal(SIGTTOU, SIG_IGN);
20     signal(SIGTTIN, SIG_IGN);
21     signal(SIGTSTP, SIG_IGN);
22     if (0 != fork()) exit(0);
23     if (-1 == setsid()) exit(0);
24     signal(SIGHUP, SIG_IGN);
25     if (0 != fork()) exit(0);
26     if (0 != chdir("/")) exit(0);
27 }
28 void do_something()
29 {
30     FILE *pf = fopen("test.tmp","wb");
31     int i = 10;
32     while(i) {
33         fwrite("aaaa\n",1,4,pf);
34         fflush(pf);
35         sleep(10);
36         i--;
37     }
38     fclose(pf);
39 }
40 void show_help(){
41     printf("run with -D to daemon mode.\n");
42 }
43 int main(int argc, char *argv[])
44 {
45     int o;
46     while(-1 != (o = getopt(argc, argv, "hDd"))) {
47         printf("%d\n", o);
48         switch(o) {
49             case 'D': daemonize(); break;
50             case 'd': break;
51             default:
52                 show_help();
53                 return -1;
54              } 
55     }
56     do_something();
57 }

 

关于daemonize()这段代码的分析,提供一个网上的介绍链接
https://blog.csdn.net/jiange_zh/article/details/50483099
详解介绍截图如下:
在这里插入图片描述

 

 

参考: https://blog.csdn.net/weixin_38134600/article/details/82802459

posted on 2019-02-13 11:27  swing07  阅读(482)  评论(0编辑  收藏  举报