int set_blocking(int sockfd) {
// 获取当前标志
int flags = fcntl(sockfd, F_GETFL, 0);
if (flags == -1) {
perror("fcntl(F_GETFL)");
return -1;
}
// 清除 O_NONBLOCK 标志
flags &= ~O_NONBLOCK;
// 设置新标志
if (fcntl(sockfd, F_SETFL, flags) == -1) {
perror("fcntl(F_SETFL)");
return -1;
}
return 0;
}
#include <fcntl.h>
int set_nonblocking(int sockfd) {
int flags = fcntl(sockfd, F_GETFL, 0); // 获取当前标志
if (flags == -1) {
perror("fcntl(F_GETFL)");
return -1;
}
if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) { // 设置 O_NONBLOCK 标志
perror("fcntl(F_SETFL)");
return -1;
}
return 0;
}