• linux 程序实现后台运行


    先上代码: 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
    ",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.
    ");
    42 }
    43 int main(int argc, char *argv[])
    44 {
    45     int o;
    46     while(-1 != (o = getopt(argc, argv, "hDd"))) {
    47         printf("%d
    ", 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

  • 相关阅读:
    Selenium+Chrome或Firefox的动态爬虫程序
    scrapy管道MySQL简记
    Ajax数据获取(未完待续。。。)
    如何快速识别网页是静态、动态、还是伪静态的?
    python3>日期和时间
    简单实例
    爬虫【基础篇】
    数据库的分区、分表、分库、分片的简介
    bilibili弹幕爬取与比对分析
    前端日常开发---搭建脚手架
  • 原文地址:https://www.cnblogs.com/swing07/p/10368879.html
Copyright © 2020-2023  润新知