怎么从Linux源码看Socket TCP的Listen及连接队列
在Linux中,socket的TCP连接是通过两个队列来管理的:Listen队列和连接队列。
Listen队列中保存着所有已经建立连接的socket,而连接队列则保存着所有正在等待建立连接的socket。当一个socket建立连接时,它会被放入到连接队列中,等待被接受。当一个socket被接受时,它会从连接队列中移除,并放入到Listen队列中。
当一个socket调用listen函数时,它会被加入到Listen队列中。当一个socket调用accept函数时,它会从Listen队列中取出一个socket,并将其放入到连接队列中。
要想从Linux源码看socket的TCP连接,首先要找到socket结构体。在include/linux/socket.h中,可以找到socket结构体的定义:
struct socket { /* * The socket state flags, including read-only flags. * * Please note: * - all flags are protected by socket_lock * - all flags except SS_PROTOREAD and SS_CANTSENDMORE are * inherited by accept()ed sockets. * - write access to some of the flags are performed using * the atomic_{set,clear}_bit() macros. Therefore, * __set_current_state() must be used while modifying the * flags, so that the set_bit() operation is not reordered * with respect to the test of the flag in the socket code. */ unsigned long state_change; socket_state state; wait_queue_head_t wait; struct file * file; struct sock * sk; const struct proto_ops * ops; };
其中socket_state是一个枚举类型,定义在include/linux/net.h中:
enum socket_state { SS_FREE = 0, /* not allocated */ SS_UNCONNECTED, /* unconnected to any socket */ SS_CONNECTING, /* in process of connecting */ SS_CONNECTED, /* connected to socket */ SS_DISCONNECTING /* in process of disconnecting */ };
可以看到,socket结构体中有一个state成员,用于保存socket的状态。当一个socket调用listen函数时,它的状态会变为SS_UNCONNECTED,当一个socket调用accept函数时,它的状态会变为SS_CONNECTING。
当一个socket建立连接时,它会被加入到连接队列中,等待被接受。当一个socket被接受时,它会从连接队列中移除,并放入到Listen队列中。
要想从Linux源码看socket的TCP连接,首先要找到socket结构体。在include/linux/socket.h中,可以找到socket结构体的定义:
struct socket { /* * The socket state flags, including read-only flags. * * Please note: * - all flags are protected by socket_lock * - all flags except SS_PROTOREAD and SS_CANTSENDMORE are * inherited by accept()ed sockets. * - write access to some of the flags are performed using * the atomic_{set,clear}_bit() macros. Therefore, * __set_current_state() must be used while modifying the * flags, so that the set_bit() operation is not reordered * with respect to the test of the flag in the socket code. */ unsigned long state_change; socket_state state; wait_queue_head_t wait; struct file * file; struct sock * sk; const struct proto_ops * ops; };
其中socket_state是一个枚举类型,定义在include/linux/net.h中:
enum socket_state { SS_FREE = 0, /* not allocated */ SS_UNCONNECTED, /* unconnected to any socket */ SS_CONNECTING, /* in process of connecting */ SS_CONNECTED, /* connected to socket */ SS_DISCONNECTING /* in process of disconnecting */ };
可以看到,socket结构体中有一个state成员,用于保存socket的状态。当一个socket调用listen函数时,它的状态会变为SS_UNCONNECTED,当一个socket调用accept函数时,它的状态会变为SS_CONNECTING。
相关文章