萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Socket 程式從 Windows 移植到 Linux 關鍵差異與跨平台宏定義

將 Socket 程式碼從 Windows 移植至 Linux,需注意以下關鍵差異:

1. 頭文件

  • Windows:winsock.h / winsock2.h
  • Linux:sys/socket.h、errno.h

2. 初始化

  • Windows:WSAStartup()
  • Linux:無需額外初始化

3. 關閉 Socket

  • Windows:closesocket()
  • Linux:close()

4. 資料型別

  • Windows:SOCKET
  • Linux:int

跨平台宏定義建議:

#ifdef WIN32
typedef int socklen_t;
typedef int ssize_t;
#endif
#ifdef __LINUX__
typedef int SOCKET;
typedef unsigned char BYTE;
typedef unsigned long DWORD;
#define FALSE 0
#define SOCKET_ERROR (-1)
#endif

5. 錯誤碼獲取

  • Windows:GetLastError() / WSAGetLastError()
  • Linux:errno 全域變數

6. 非阻塞模式設定

  • Windows:ioctlsocket()
  • Linux:fcntl()

7. send() 最後參數

  • Windows:通常設 0
  • Linux:建議 MSG_NOSIGNAL,否則對方關閉連線時程序可能因 SIGPIPE 異常終止

8. 毫秒級時間獲取

  • Windows:GetTickCount()
  • Linux:gettimeofday()

多執行緒對照表

WindowsLinux
process.hpthread.h
_beginthreadpthread_create
_endthreadpthread_exit
copyright © 萬盛學電腦網 all rights reserved