sys_socket()的代码流程图如下所示:
从上面的代码及流程图中,可以看到sys_socket()主要调用sock_create()和sock_map_fd()来完成创建套接字的工作,在讨论这两个函数之前,要强调一下type参数。从linux 2.6.27开始,参数type除了指定套接字类型外,还可以通过或运算来指定SOCK_CLOEXEC和SOCK_NONBLOCK标志来改变套接字的行为。可以通过man socket命令来查看,原文是:
Since Linux 2.6.27, the type argument serves a second purpose: in addition to specifying a
socket type, it may include the bitwise OR of any of the following values, to modify the
behavior of socket():
SOCK_NONBLOCK Set the O_NONBLOCK file status flag on the new open file description. Using
this flag saves extra calls to fcntl(2) to achieve the same result.
SOCK_CLOEXEC Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. See the
description of the O_CLOEXEC flag in open(2) for reasons why this may be
useful.
一、sock_create()函数
sock_create()函数时对__sock_create()函数的简单封装,__sock_create()函数的代码流程图如下所示:
__sock_create()调用sock_alloc()分配一个新的inode和socket对象,并设置套接字的权限位及套接字所属的用户和用户组。如果要创建的是TCP套接字,pf->create()中的pf是inet_family_ops变量,该变量的类型是net_proto_family结构,在net/ipv4/if_inet