socket系统调用-文件相关

本文探讨了socket系统调用中如何通过文件描述符管理socket与file结构的关系。介绍了sock_map_fd()如何将socket与file绑定,并将其添加到进程的文件指针数组中。此外,还讲解了sock_alloc_file()函数创建file结构体并设置socket相关的文件操作函数,以及如何通过sockfd_lookup_light和sock_from_file()来查找和获取相应的socket。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sock_map_fd()

获取文件描述符,创建file结构实例;socket与file绑定,将file结构添加到进程打开的文件指针数组中。

寻思着,根据fd,找到file;根据file找到socket。

E:\linux-4.1.45\linux-4.1.45\net\socket.c
static int sock_map_fd(struct socket *sock, int flags)
{
	struct file *newfile;
	int fd = get_unused_fd_flags(flags);//获取未使用的文件描述符
	if (unlikely(fd < 0))
		return fd;

	newfile = sock_alloc_file(sock, flags, NULL);
	if (likely(!IS_ERR(newfile))) {
		fd_install(fd, newfile);//将file结构添加到进程打开的文件指针数组中。
		return fd;
	}

	put_unused_fd(fd);
	return PTR_ERR(newfile);
}

sock_alloc_file()

在这个函数中创建file结构体,其文件操作函数为socket_file_ops;将socket与file绑定。

E:\linux-4.1.45\linux-4.1.45\net\socket.c
/*
 *	Obtains the first available file descriptor and sets it up for use.
 *
 *	These functions create file structures and maps them to fd space
 *	of the current process. On success it re
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值