C語言getopt()函數:分析命令行參數
頭文件
#include <unistd.h>
定義函數:
int getopt(int argc, char * const argv[], const char * optstring);
函數說明:getopt()用來分析命令行參數。
1、參數argc 和argv 是由main()傳遞的參數個數和內容。
2、參數optstring 則代表欲處理的選項字符串。
此函數會返回在argv 中下一個的選項字母,此字母會對應參數optstring 中的字母。
如果選項字符串里的字母后接著冒號":",則表示還有相關的參數,全域變量optarg 即會指向此額外參數。
如果getopt()找不到符合的參數則會印出錯信息,并將全域變量optopt 設為"?"字符, 如果不希望getopt()印出錯信息,則只要將全域變量opterr 設為0 即可。
返回值:如果找到符合的參數則返回此參數字母, 如果參數不包含在參數optstring 的選項字母則返回"?"字符,分析結束則返回-1.
范例
#include <stdio.h>#include <unistd.h>int main(int argc, char **argv){ int ch; opterr = 0; while((ch = getopt(argc, argv, "a:bcde")) != -1) switch(ch) { case 'a': printf("option a:'%s'/n", optarg); break; case 'b': printf("option b :b/n"); break; default: printf("other option :%c/n", ch); } printf("optopt +%c/n", optopt);}
執行:
$. /getopt -boption b:b$. /getopt -cother option:c$. /getopt -aother option :?$. /getopt -a12345option a:'12345'
C語言select()函數:I/O多工機制
定義函數:
int select(int n, fd_set * readfds, fd_set * writefds, fd_set * exceptfds, struct timeval * timeout);
函數說明:select()用來等待文件描述詞狀態的改變. 參數n 代表最大的文件描述詞加1, 參數readfds、writefds 和exceptfds 稱為描述詞組, 是用來回傳該描述詞的讀, 寫或例外的狀況. 底下的宏提供了處理這三種描述詞組的方式:
參數 timeout 為結構timeval, 用來設置select()的等待時間, 其結構定義如下:
struct timeval{ time_t tv_sec; time_t tv_usec;};
返回值:如果參數timeout 設為NULL 則表示select ()沒有timeout.
錯誤代碼:執行成功則返回文件描述詞狀態已改變的個數, 如果返回0 代表在描述詞狀態改變前已超過timeout 時間, 當有錯誤發生時則返回-1, 錯誤原因存于errno, 此時參數readfds, writefds, exceptfds 和timeout的值變成不可預測。
范例:
常見的程序片段:
fs_set readset;FD_ZERO(&readset);FD_SET(fd, &readset);select(fd+1, &readset, NULL, NULL, NULL);if(FD_ISSET(fd, readset){...}
新聞熱點
疑難解答
圖片精選