C語言中getopt()函數(shù)和select()函數(shù)的使用方法
C語言getopt()函數(shù):分析命令行參數(shù)
頭文件
#include <unistd.h>
定義函數(shù):
int getopt(int argc, char * const argv[], const char * optstring);
函數(shù)說明:getopt()用來分析命令行參數(shù)。
1、參數(shù)argc 和argv 是由main()傳遞的參數(shù)個數(shù)和內容。
2、參數(shù)optstring 則代表欲處理的選項字符串。
此函數(shù)會返回在argv 中下一個的選項字母,此字母會對應參數(shù)optstring 中的字母。
如果選項字符串里的字母后接著冒號":",則表示還有相關的參數(shù),全域變量optarg 即會指向此額外參數(shù)。
如果getopt()找不到符合的參數(shù)則會印出錯信息,并將全域變量optopt 設為"?"字符, 如果不希望getopt()印出錯信息,則只要將全域變量opterr 設為0 即可。
返回值:如果找到符合的參數(shù)則返回此參數(shù)字母, 如果參數(shù)不包含在參數(shù)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); }
執(zhí)行:
$. /getopt -b option b:b $. /getopt -c other option:c $. /getopt -a other option :? $. /getopt -a12345 option a:'12345'
C語言select()函數(shù):I/O多工機制
定義函數(shù):
int select(int n, fd_set * readfds, fd_set * writefds, fd_set * exceptfds, struct timeval * timeout);
函數(shù)說明:select()用來等待文件描述詞狀態(tài)的改變. 參數(shù)n 代表最大的文件描述詞加1, 參數(shù)readfds、writefds 和exceptfds 稱為描述詞組, 是用來回傳該描述詞的讀, 寫或例外的狀況. 底下的宏提供了處理這三種描述詞組的方式:
- FD_CLR(inr fd, fd_set* set); 用來清除描述詞組set 中相關fd 的位
- FD_ISSET(int fd, fd_set *set); 用來測試描述詞組set 中相關fd 的位是否為真
- FD_SET(int fd, fd_set*set); 用來設置描述詞組set 中相關fd 的位
- FD_ZERO(fd_set *set); 用來清除描述詞組set 的全部位
參數(shù) timeout 為結構timeval, 用來設置select()的等待時間, 其結構定義如下:
struct timeval { time_t tv_sec; time_t tv_usec; };
返回值:如果參數(shù)timeout 設為NULL 則表示select ()沒有timeout.
錯誤代碼:執(zhí)行成功則返回文件描述詞狀態(tài)已改變的個數(shù), 如果返回0 代表在描述詞狀態(tài)改變前已超過timeout 時間, 當有錯誤發(fā)生時則返回-1, 錯誤原因存于errno, 此時參數(shù)readfds, writefds, exceptfds 和timeout的值變成不可預測。
- EBADF 文件描述詞為無效的或該文件已關閉
- EINTR 此調用被信號所中斷
- EINVAL 參數(shù)n 為負值.
- ENOMEM 核心內存不足
范例:
常見的程序片段:
fs_set readset; FD_ZERO(&readset); FD_SET(fd, &readset); select(fd+1, &readset, NULL, NULL, NULL); if(FD_ISSET(fd, readset){...}
相關文章
C語言中sizeof()與strlen()函數(shù)的使用入門及對比
這篇文章主要介紹了C語言中sizeof()與strlen()函數(shù)的使用入門及對比,同時二者在C++中的使用情況也基本上同理,是需要的朋友可以參考下2015-12-12