C語言中g(shù)etopt()函數(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ù)個(gè)數(shù)和內(nèi)容。
2、參數(shù)optstring 則代表欲處理的選項(xiàng)字符串。
此函數(shù)會(huì)返回在argv 中下一個(gè)的選項(xiàng)字母,此字母會(huì)對(duì)應(yīng)參數(shù)optstring 中的字母。
如果選項(xiàng)字符串里的字母后接著冒號(hào)":",則表示還有相關(guān)的參數(shù),全域變量optarg 即會(huì)指向此額外參數(shù)。
如果getopt()找不到符合的參數(shù)則會(huì)印出錯(cuò)信息,并將全域變量optopt 設(shè)為"?"字符, 如果不希望getopt()印出錯(cuò)信息,則只要將全域變量opterr 設(shè)為0 即可。
返回值:如果找到符合的參數(shù)則返回此參數(shù)字母, 如果參數(shù)不包含在參數(shù)optstring 的選項(xiàng)字母則返回"?"字符,分析結(jié)束則返回-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多工機(jī)制
定義函數(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 中相關(guān)fd 的位
- FD_ISSET(int fd, fd_set *set); 用來測(cè)試描述詞組set 中相關(guān)fd 的位是否為真
- FD_SET(int fd, fd_set*set); 用來設(shè)置描述詞組set 中相關(guān)fd 的位
- FD_ZERO(fd_set *set); 用來清除描述詞組set 的全部位
參數(shù) timeout 為結(jié)構(gòu)timeval, 用來設(shè)置select()的等待時(shí)間, 其結(jié)構(gòu)定義如下:
struct timeval { time_t tv_sec; time_t tv_usec; };
返回值:如果參數(shù)timeout 設(shè)為NULL 則表示select ()沒有timeout.
錯(cuò)誤代碼:執(zhí)行成功則返回文件描述詞狀態(tài)已改變的個(gè)數(shù), 如果返回0 代表在描述詞狀態(tài)改變前已超過timeout 時(shí)間, 當(dāng)有錯(cuò)誤發(fā)生時(shí)則返回-1, 錯(cuò)誤原因存于errno, 此時(shí)參數(shù)readfds, writefds, exceptfds 和timeout的值變成不可預(yù)測(cè)。
- EBADF 文件描述詞為無效的或該文件已關(guān)閉
- EINTR 此調(diào)用被信號(hào)所中斷
- EINVAL 參數(shù)n 為負(fù)值.
- ENOMEM 核心內(nèi)存不足
范例:
常見的程序片段:
fs_set readset; FD_ZERO(&readset); FD_SET(fd, &readset); select(fd+1, &readset, NULL, NULL, NULL); if(FD_ISSET(fd, readset){...}
相關(guān)文章
C語言中sizeof()與strlen()函數(shù)的使用入門及對(duì)比
這篇文章主要介紹了C語言中sizeof()與strlen()函數(shù)的使用入門及對(duì)比,同時(shí)二者在C++中的使用情況也基本上同理,是需要的朋友可以參考下2015-12-12C語言多功能動(dòng)態(tài)通訊錄實(shí)現(xiàn)示例
這篇文章主要為大家介紹了C語言多功能動(dòng)態(tài)通訊錄實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01