写操作


读操作


accept


connect


非阻塞connect和epoll

Python例子:

import time
import socket
import select

if "EPOLLRDHUP" not in dir(select):
    select.EPOLLRDHUP = 0x2000
epoll = select.epoll()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(False)

try:
    sock.connect(("127.0.0.1", 80))
except IOError as ex: 
    if ex.errno != socket.errno.EINPROGRESS:
        raise

epoll.register(sock.fileno(), 
    select.EPOLLIN | select.EPOLLOUT | 
    select.EPOLLERR | select.EPOLLHUP | 
    select.EPOLLRDHUP)

while True:
    time.sleep(0.02)
    events = epoll.poll()
    if not events:
        continue

    for fd, event in events:
        if event & select.EPOLLIN:
            print "in"
        if event & select.EPOLLOUT:
            print "out"
        if event & select.EPOLLERR:
            print "err"
        if event & select.EPOLLHUP:
            print "hup"
        if event & select.EPOLLRDHUP:
            print "rdhup"
    break
sock.close()

Posix 定义了两条与 select 和 非阻塞 connect 相关的规定: