第2章 編寫優質GNU/Linux軟體
1.與運行環境互動
擷取參數:主要採用getopt和getopt_long函數
標頭檔 #include<unistd.h> 或 <getopt.h>
函數原型 int getopt(int argc,char * const argv[ ],const char * optstring);
int getopt_long(int argc, char * const argv[], const char *optstring,const struct option *longopts, int *longindex);
參數說明 參數argc和argv是由main()傳遞的參數個數和內容。
參數 optstring為選項字串, 告知 getopt()可以處理哪個選項以及哪個選項需要參數,
如果選項字元後無冒號, 表示參數選項不包含參數,處理時忽略參數。
如果選項字元後跟冒號":", 表示參數選項含有參數,跟在參數選項後的一字串為該選項的參數
如果選項字元後跟雙冒號"::", 表示該選項的參數為可選,根據具體的命令而定。(不是所有Linux都支援)
longopts 是結構數組,用來指明短參數對應的長參數,使用如下結構:
struct option {
const char *name;// 長選項的名字
int has_arg;// 是否有參數:0沒有
int *flag;//如何返回長選項的結果,一般為NULL
int val;//將要返回的結果,可以理解為對應的短選項
};類似這種:
const struct option long_options[] = {
{ "help", 0, NULL, 'h' },
{ "output", 1, NULL, 'o' },
{ "verbose", 0, NULL, 'v' },
{ NULL, 0, NULL, 0}//數組中最後一個元素的所有域都應為 0
};
extern char *optarg;
extern int optind, opterr, optopt;
全域變數optarg 指向當前選項的參數,如果沒有參數則為空白。
2. stdout 是經過緩衝處理的
在C++中,cout和cerr之間也有這樣的區別。注意endl操作符除了輸出分行符號,還會執行重新整理操作;如果你不希望執行重新整理操作(例如出於運行效率的考慮)則應該使用常量'\n'表示換行。
3. 環境變數:
environ數組包含了所有環境變數,使用時需要extern char** environ;
不要直接修改 environ 變數;如果需要修改環境變數,則應通過 setenv 和 unsetenv 函數完成。
4.臨時檔案
5. 編寫並使用程式庫
封存檔案
6. 共用庫
7.動態載入與卸載
第4章 線程
1. C++中線程清理方法