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