TCP/IP程式設計之fcntl函式詳解
阿新 • • 發佈:2019-01-31
fcntl函式可執行各種描述符操作,在這裡我們只需要關心如何設定套接字為非阻塞式I/O
函式原型:
FCNTL(2) Linux Programmer's Manual FCNTL(2) NAME fcntl - manipulate file descriptor SYNOPSIS #include <unistd.h> #include <fcntl.h> int fcntl(int fd, int cmd, ... /* arg */ );
返回值:
返回:若成功則取決於cmd,若出錯則為-1
開啟非阻塞式I/O:
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> //設定非阻塞 static void setnonblocking(int sockfd) { int flag = fcntl(sockfd, F_GETFL, 0); //不能直接覆蓋原標識,先獲取 if (flag < 0) { perror("fcntl F_GETFL fail"); return; } if (fcntl(sockfd, F_SETFL, flag | O_NONBLOCK) < 0) { perror("fcntl F_SETFL fail"); } }
關閉非阻塞式I/O:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
//取消非阻塞
static void setblocking(int sockfd) {
int flag &= ~O_NONBLOCK;
if (fcntl(sockfd, F_SETFL, flag) < 0) {
perror("fcntl F_SETFL fail");
}
}
參考:《unix網路程式設計》·卷1