阻塞即同步,一件事情沒有完成必然不會往下執行;
非阻塞即異步,不管目前事情有沒有完成,都會往下執行;
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...
}