在上篇文章中,已经介绍了关于命令行参数解析,对于getopt和getopt_long的使用是相当熟悉了,今天将是通过一个glib的一个接口:g_spawn_command_line_sync()通过管道产生一个同步运行的子进程,然后通过getopt_long去解析,执行相应的程序。
1、写一个getopt_long 的main.c
- #include <getopt.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <gtk/gtk.h>
- static void display_usage(const char* program, FILE* fp, int exit_code)
- {
- fprintf(fp, "usage: %s --level [0-9] --thme [theme name] [options]/n", program);
- fprintf(fp, "-l --level [init-level]/n");
- fprintf(fp, "-t --theme [theme-name]/n");
- fprintf(fp, "-s --sound [true/false]/n");
- fprintf(fp, "-p --progressbar[true/false]/n");
- fprintf(fp, "-h --help /n");
- exit(exit_code);
- }
- int main(int argc, char** argv)
- {
- gint opt = 0;
- int run_level = 0;
- char* theme = NULL;
- gboolean sound = FALSE;
- gboolean progressbar = FALSE;
- const struct option options[]=
- {
- {"level", 1, NULL, 'l'},
- {"theme", 1, NULL, 't'},
- {"sound", 1, NULL, 's'},
- {"progressbar", 1, NULL, 'p'},
- {"help", 0, NULL, 'h'},
- {NULL, 0, NULL, 0}
- };
- optind = 0;
- while((opt = getopt_long(argc, argv, "", options, NULL)) != -1)
- {
- switch(opt)
- {
- case 'l':
- {
- run_level = atoi (optarg);
- if( run_level < 0 || run_level > 9)
- {
- display_usage(argv[0], stdout, 0);
- }
- break;
- }
- case 't':
- {
- theme = optarg;
- break;
- }
- case 's':
- {
- if(!strcmp(optarg, "true"))
- {
- sound = TRUE;
- }
- break;
- }
- case 'p':
- {
- if(!strcmp(optarg, "true"))
- {
- progressbar = TRUE;
- }
- break;
- }
- case 'h':
- {
- display_usage(argv[0], stdout, 0);
- break;
- }
- default:
- {
- display_usage(argv[0], stderr, 1);
- break;
- }
- }
- }
- printf("level = %d, theme = %s, sound = %d, progressbar = %d./n", run_level, theme, sound, progressbar);
- return 0;
- }
3、通过编译产生一个执行文件:preview_test.下面的函数将会通过调用这个执行文件,创建另一个进程,执行它的程序。
4、打开另外一个终端,写一个调试函数main.c
- #include <gtk/gtk.h>
- #include <stdio.h>
- #include <string.h>
- int main(int argc, char** argv)
- {
- char cmdline[256] = {0};
- char* file_path = strdup("/home/wutangzhi/project/getopt_long_project/");
- sprintf(cmdline, "%spreview_test --level 5 --theme default --sound true --progressbar true", file_path);
- g_printf("file_path = %s/n", cmdline);
- if(!g_spawn_command_line_sync(cmdline, NULL, NULL, NULL, NULL))
- {
- g_printf("[ %s ]: preview_test couldn't be execute!/n", __func__);
- return -1;
- }
- return 0;
- }
调试结果:
- file_path = /home/wutangzhi/project/getopt_long_project/preview_test --level 5 --theme default --sound true --progressbar true
- level = 5, theme = default, sound = 1, progressbar = 1.
从这个实例应该更加明白了getopt_long的使用,其中也领会了g_spawn_command_line_s
ync()的简单用法。glib把它封装得很好。适当的时候使用它们,会收到相当好的效果的。