winsock not supporting read/write

我怕爱的太早我们不能终老 提交于 2020-01-10 04:18:47

问题


With a small test program (compiled with mingw on Linux), I noticed that one cannot use the read and write calls on the socket fd as obtained using Winsock2's implementation of the socket call. The write call returns <0 and sets errno=EBADF.

Think of programs run from xinetd, minus their assumption that their stdin/stdout always is a socket. (Some programs do call getpeername for example, which will fail if it is not a socket, subsequently they may exit prematurely.)

So how are {file descriptor type}-agnostic programs that just read/write from/to stdin/stdout supposed to reasonably work in the win32 environment unless making assumptions about the fd?

Or more simply put, is there some magic function call to be executed to wire up Winsock2 socket fds with the win32 (well, mingw) write implementation?


回答1:


If you want any kind of sane behavior on Windows, forget about mingw. It uses the MSVC++ standard library, which can't even manage to conform to the plain C standard, much less POSIX. Sadly cygwin is a bit bloated, but I would just accept the bloat as the price of programming for Windows and go with cygwin. Or you can write 2 different versions of every program you write, possibly entangled with #ifdefs, to support both MSVC and POSIX...




回答2:


The read() and write() functions are POSIX I/O system calls, not socket API calls.

MinGW is for compiling to the native Windows platform. It does not provide a POSIX environment.

When using MinGW with Winsock, you have two options:

  1. Use the socket API calls send() and recv().
  2. Use the Windows I/O system calls WriteFile() and ReadFile().



回答3:


Socket handles on Windows are not file handles. You have to use Winsock functions to read/write/change state.

Neither can you use select or its ilk consistently with other types of handles in Windows.



来源:https://stackoverflow.com/questions/4778043/winsock-not-supporting-read-write

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!