天天看點

linux sync指令到底做了什麼(結合項目中遇到的問題)

很久前儲存的一片文章, 不清楚具體出處了.

[cpp]  view plain  copy

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

繼續閱讀