在Unix中,一切皆是文件的理念支持read()
、write()
和close()
函数,但在Win32上不支持。
我想模仿这种方式,但不知道如何区分WinSocks2中的sock
是socket还是fd。
//returns 1 if `sock` is network socket,
// 0 if `sock` is file desriptor (including stdio, stderr, stdout), ...
// -1 in none of above
int is_net_socket(int sock)
{
// ...?
}
这应该按照以下方式工作:
int mysock = socket(PF_INET, SOCK_STREAM, 0);
int myfd = _open("my_file.txt", _O_RDONLY);
printf("1: %d 2: %d 3: %d 4:%d\n",
is_net_socket(mysock), //1
is_net_socket(myfd), //0
is_net_socket(stdin), //0
is_net_socket(stderr)); //0
// should print "1: 1 2: 0 3: 0 4:0"
如何实现 is_net_socket
并将其用于以下目的:int my_close(int sock)
{
#if ON_WINDOWS
switch( is_net_socket(sock) ) {
case 1: return closesocket(sock);
case 0: return _close(sock);
default: //handle error...
}
#else
return close(sock);
#endif
}