vxWorks Socket非阻塞(查询)模式数据接收recvform()小析
2012-06-12 22:05阅读:
本文仅针对UDP通信方式的Socket,从程序上来说就是使用sendto()和recvfrom()进行数据发送和接收的通信方式。UDP通信方式的socket存在阻塞和非阻塞模式(blocking
or non-blocking),他们是什么区别呢?
recvfrom()以阻塞套接字为参数调用该函数接收数据,如果此时套接字缓冲区内没有数据可读,则调用线程在数据到来前一直睡眠。对于多对象的通信系统,这样做的好处很明显,可以节约大量的系统资源,使CPU在recvfrom()阻塞的线程(任务)之外处理更多的事情。这也是vxWorks下socket通信最常用的方式,且vxWorks默认使用阻塞模式。
非阻塞模式的recvfrom()函数被调用时,若套接字缓冲区内没有数据,将立即返回(-1),直到套接字缓冲区内有数据时,才会将缓冲区内的数据拷贝至应用程序缓冲区,并返回拷贝的字节数目。非阻塞模式也成为查询模式,使用非阻塞模式往往是任务需要recvfrom在任何被调用的时刻均返回,便于进一步处理,特别是监督任务状态,以及其他特殊应用。
从手册中我们可以查到如何设置vxWorks操作系统的socket为非阻塞模式:
Sockets respond to the following ioctl(
) functions. These functions are defined in the header
files ioLib.h and ioctl.h.
- FIONBIO
- Turns on/off non-blocking I/O. on = TRUE; status = ioctl (sFd,
FIONBIO, &on);
- FIONREAD
- Repo
rts the number of read-ready bytes available on the socket. On the
return of
ioctl(
),
bytesAvailable has the number of bytes
available to read from the socket. status = ioctl (sFd, FIONREAD,
&bytesAvailable);
- SIOCATMARK
- Reports whether there is out-of-band data to be read from the
socket. On the return of ioctl(
), atMark is TRUE (1) if there is out-of-band
data. Otherwise, it is FALSE (0). status = ioctl (sFd, SIOCATMARK,
&atMark);
To use this feature, include the following component:
INCLUDE_BSD_SOCKET
使用实例:
int iMode = 1; //0:阻塞
ioctlsocket(socketc,FIONBIO, (u_long FAR*)
&iMode);//非阻塞设置
rs=recvfrom(socketc,rbuf,sizeof(rbuf),0,(SOCKADDR*)&addr,&len);
注意非阻塞模式下,在套接字缓冲区没有数据时,将返回(-1),应用程序应考虑到此返回。
工程应用时,还需要深入实验。