發表文章

目前顯示的是 12月, 2016的文章

Write FD set 的用途

一段時間,我其實都不知道 select 和 epoll 這一類 function 裏面的 writefds 到底有什麼用。read fd set很容易理解,那就是有東西要讀,或者白話一點,收到封包了。那 write fd set 到底要幹嘛呢?直到今天遇到了一個情境我才使用了它 ... 在寫 TCP socket 程式的時候,會使用到 connect 這個函式。一般來說, connect 這個函式是 blocking 的,也就是會一直到事情做完才會返回。但如果將 socket 設定成 non-blocking 模式呢?這時候 connect 會立刻返回並將 error no 設定為 EINPROGRESS 。下面是"男人"的解釋: EINPROGRESS               The  socket  is  nonblocking and the connection cannot be completed immediately. It is possible to select(2) or poll(2) for completion by  selecting  the  socket  for  writing.   After select(2) indicates writability , use getsockopt(2) to read  the SO_ERROR option at level SOL_SOCKET to determine whether connect() completed successfully  ( SO_ERROR is zero ) or unsuccessfully ( SO_ERROR is one of the usual  error codes listed here, explaining the reason for the failure ). 好了,這時候我們可以看到 select 可以用來判斷 connect 是否完成。範例程式碼如下: #include // for printf() and fprintf() #include // for socket(), connect(), send(), and recv() #

如何透過 Python 來呼叫 ioctl

首先,先來抄一段 wikipedia 的定義: In computing, ioctl (an abbreviation of input/output control ) is a system call for device-specific input/output operations and other operations which cannot be expressed by regular system calls. It takes a parameter specifying a request code ; the effect of a call depends completely on the request code. Request codes are often device-specific. 簡單來說,ioctl 是針對 device 去做輸入輸出(白話一點,get/set)操作的一種方式,在 Linux 底下,所有的 kernel module 都可以被視做是一個 device,所以把 ioctl 當作一種 UK 的溝通機制也未嘗不可。不過如果要傳大量資料的話還是採用其他的方式比較妥當,像是 netlink 。在溝通的時候,User Space 和 Kernel Space 必須先定義好雙方溝通的格式。最常見的範例基本上就是 ifconfig 這隻程式了,在這裡也不去看它,反正是一支很簡單的 C 程式。 本篇要紀錄的是,在 Python 裡要怎麼呼叫 ioctl。範例很簡單,,就是實作一支類似 ifconfig 的程式(不過只有 get,懶得寫 set)。直接放在下面: #!/usr/bin/python import socket import fcntl import sys import struct import array def get_if_list (): try : fd = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) # #define SIOCGIFCONF 0x8912 /* get iface list