Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7770790
  • 博文数量: 701
  • 博客积分: 2150
  • 博客等级: 上尉
  • 技术积分: 13233
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-29 16:28
个人简介

天行健,君子以自强不息!

文章分类

全部博文(701)

文章存档

2019年(2)

2018年(12)

2017年(76)

2016年(120)

2015年(178)

2014年(129)

2013年(123)

2012年(61)

分类: C/C++

2015-05-29 10:52:26

一个命令行解析与程序开启后台模式运行的示例程序。
闲言少述,直接上代码:

/* Parse command parameters
 *
 * by Hank
 * 2015/5/27
 */
#include
#include
#include
#include
#include
#include
#include


#include     // to catch Ctrl-C
#include
#include
#include
#include




int
main(int argc, char **argv)
{
    char const *short_options = "d:p:h:e:w:i:f:";
    struct option const long_options[] = {
        { "daemon"  , 0, NULL, 'd' },
        { "port"    , 1, NULL, 'p' },
        { "key"     , 1, NULL, 'i' },
        { "dir"     , 1, NULL, 'e' },
        { "listen"  , 1, NULL, 'w' },
        { "filename", 1, NULL, 'f' },
        { "help"    , 0, NULL, 'h' },
        { NULL },
    };

    int  daemon = 0;
    char *filename = NULL, *dir = NULL;
    int  port = 0, listen=0;
    int key=0;

    for (;;)
    {
        int next_option = getopt_long(argc, argv, short_options, long_options, NULL);
        if (next_option == -1)
          break;
        switch (next_option)
        {
            case 'd': daemon  = 1;            break;
            case 'p': port    = atoi(optarg); break;
            case 'i': key      = atoi(optarg); break;
            case 'f': filename= optarg;       break;
            case 'e': dir     = optarg;       break;
            case 'w': listen   = atoi(optarg); break;
            case 'h': printf("TEST [-d] [-h] <-p port> <-i key> <-w listen-port> [-e log-dir]\n");  break;
        }
    }

    if (0 == port || NULL == filename || 0 == listen || 0 == key)
    {
        printf("TEST [-d] [-h]<-i key>  <-p port> <-f file> <-w listen-port> [-e log-dir]\n");
        goto MAINQUIT;
    }

    if (daemon)
    {
        pid_t pid = fork();
        if (pid < 0)
          return 0;
        if (pid > 0) exit(0);


        if (setsid() < 0)
        {
            printf ("%d \n",key);
            goto MAINQUIT;
        }

        close(0);
        close(1);
        close(2);
        open("/dev/null", O_RDONLY);
        pid = getpid();
        char buf[1024], str[1024];
        struct tm tm;
        time_t t = time(0);
        localtime_r(&t, &tm );
        strftime(str,1024,"%Y%m%d%H%M%S",&tm);

        if (!dir)
          dir = ".";
        snprintf(buf, 1024, "%s/%d_%s_status.log", dir, pid, str);
        open(buf, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR);
        snprintf(buf, 1024, "%s/%d_%s_trace.log", dir, pid, str);
        open(buf, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR);
    }

MAINQUIT:
    return 0;
}

编译命令行:
gcc -g -Wall  -o test main.c 

命令行:
./test -i 22 -e /opt -p 8080 -w 8088 -f ./test.conf -d 
阅读(2048) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~