问题
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 #ifdef
s, 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:
- Use the socket API calls
send()
andrecv()
. - Use the Windows I/O system calls
WriteFile()
andReadFile()
.
回答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