Determine between socket and fd

后端 未结 4 675
挽巷
挽巷 2021-02-13 06:04

On unix everything is a file approach of function read(), write(), close() is not supported on Win32.

I

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 06:50

    I suppose you can use select to query the status of a socket.

    http://msdn.microsoft.com/en-us/library/ms740141%28VS.85%29.aspx

    I would recommend grouping your file desc and sockets in a single struct. You can declare an enum to tell if the descriptor is a file or socket. I know this might not be as dynamic as you want, but generally when you create portable applications, its best to abstract those details away.

    Example:

    enum type { SOCKET, FILE };
    
    typedef struct
    {
        unsigned int id;
        type dataType;
    } descriptor_t;
    
    int close(descriptor_t sock)
    {
    #if WIN32
        if (sock.dataType == SOCKET)
            return closesocket(sock.id);
        else
            return _close(sock.id);
    #else
        return close(sock.id);
    #endif
    }
    

提交回复
热议问题