很久前儲存的一片文章, 不清楚具體出處了.
[cpp] view plain copy
- #include <config.h>
- #include <getopt.h>
- #include <stdio.h>
- #include <sys/types.h>
- #include "system.h"
- #include "error.h"
- #include "long-options.h"
- #define PROGRAM_NAME "sync"
- #define AUTHORS "Jim Meyering"
- char *program_name;
- void
- usage (int status)
- {
- if (status != EXIT_SUCCESS) //EXIT_SUCCESS是個宏定義,在linux系統中被定義成0,代表成功退出狀态
- fprintf (stderr, _("Try `%s --help' for more information.\n"),
- program_name);//fprintf接受的第一個參數是輸出的目的地,這是個FILE * 類型的流
- //後面的參數是格式化輸出,類似printf了,不知道這個加了下劃線和括号的文法是何物?
- //第三個參數是對應%s的
- else //如果usage接收到的整型類型形參status等于宏EXIT_SUCCESS,則執行下面的語句塊
- {
- //這段語句塊也是一系列的輸出,解釋一下fputs吧,第一個參數是指向字元類型的指針,第二個參數是目的地流
- printf (_("Usage: %s [OPTION]\n"), program_name);//輸出類似: Usage: sync [OPTION]
- fputs (_("\
- Force changed blocks to disk, update the super block.\n\
- \n\
- "), stdout);//向标準輸出,輸出一串字元串
- fputs (HELP_OPTION_DESCRIPTION, stdout);//是在System.h中定義的宏,其值為:
- // _(" --help display this help and exit\n")
- fputs (VERSION_OPTION_DESCRIPTION, stdout);//同上,也是個宏
- printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);//PACKAGE_BUGREPORT這個宏定義沒有找到,估計是在lib下面的頭檔案裡定義的。
- }
- exit (status); //最後函數的傳回值是傳入的形參status的值
- }
- int
- main (int argc, char **argv) //标準的main函數
- {
- initialize_main (&argc, &argv);//應該是為了相容posix标準而調的在System.h裡面定義的一個宏,我檢視了預編譯後的實際代碼,
- //結果是個空語句,說明其實沒有什麼用處,估計開源的程式都這樣寫,而在非linux平台,像System.h裡面的initialize_main宏,應該有定義。
- program_name = argv[0];//給全局字元指針變量program_name指派,我看很多程式都這樣做,估計這應該是标準做法
- setlocale (LC_ALL, "");//意思是将整個locale設定為實作相關的本地環境,有點拗口,我了解就是恢複locale為本地的預設環境
- bindtextdomain (PACKAGE, LOCALEDIR);
- textdomain (PACKAGE);//這兩句也是在System.h裡面定義的宏,預編譯後也是空語句,标準做法
- atexit (close_stdout);//當這個程式(main函數)正常結束後,close_stdout被調用,看看man,對atexit等函數解釋的相當到位了,不過我沒有找到close_stdout的定義
- parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, VERSION,
- usage, AUTHORS, (char const *) NULL);
- if (getopt_long (argc, argv, "", NULL, NULL) != -1)
- usage (EXIT_FAILURE);//沒有參數,列印幫助,提示看--help
- if (optind < argc)//optind是傳遞給main函數的argv裡的第一個不是選項參數的下标,如果這個下标比指令行參數個數還小
- error (0, 0, _("ignoring all arguments"));//則調用error函數,傳遞了3個參數
- sync ();//調用函數sync
- exit (EXIT_SUCCESS);//最後傳回成功執行的狀态碼。
- }