阻塞即同步,一件事情没有完成必然不会往下执行;
非阻塞即异步,不管当前事情有没有完成,都会往下执行;
linux socket下面,最常用的函数便是recvfrom/sendto, recv/send,前面那一对是基于UDP的,后面是基于TCP。这两组函数都有阻塞和非阻塞方式,可以通过fcntl函数设置。
说到这里,顺便提一下fcntl函数,这个系统调用是用来重新设置打开设备/文件的属性,包括读、写、非阻塞等,而无需重新打开文件。
值得一提的是,采用非阻塞形式的I/O可以用来编写简单的心跳检测程序,测试服务器是否在运行。代码之后补充。。。。。。
基本流程如下:
if (-1 == fcntl(fd, F_SETFL, O_NONBLOCK))// set the fd to nonblock
{ printf("fcntl socket error!\n");
return -1;
}
fd_set readfds;
FD_ZERO(&readfds);//clean
FD_SET(fd, &readfds);//add
struct timeval tv={mysec,0};//set the time
if (selectfd+1,&readfds,NULL, NULL, &tv) > 0){
recvfrom/recv();
printf("recv data from server in %d secs\n", mysec);//server is working...
}
else{
printf("don't recv data from server in %d secs\n", mesec);//server isn't working...
}