gpt4 book ai didi

c - sendmsg 是如何工作的?

转载 作者:太空狗 更新时间:2023-10-29 16:37:32 24 4
gpt4 key购买 nike

如您所知,sendmsg 有这样的声明:

int sendmsg(int s, const struct msghdr *msg, int flags);

msghdr结构有这种形式:

struct msghdr {
void * msg_name; /* optional address */
socklen_t msg_namelen; /* size of address */
struct iovec * msg_iov; /* scatter/gather array */
size_t msg_iovlen; /* # elements in msg_iov */
void * msg_control; /* ancillary data, see below */
socklen_t msg_controllen; /* ancillary data buffer len */
int msg_flags; /* flags on received message */
};

如您所见,msghdr 有一个缓冲区数组 iovec 和缓冲区计数 msg_iovlen。我想知道 sendmsg 如何发送这些缓冲区。它是连接所有缓冲区并发送还是在 for 循环中发送?

最佳答案

联机帮助页谈到一条消息(单数)和多个元素(复数):

For send() and sendto(), the message is found in buf and has length len. For sendmsg(), the message is pointed to by the elements of the array msg.msg_iov. The sendmsg() call also allows sending ancillary data (also known as control information).

对于流套接字,这两种方式都不重要。您发送的任何数据最终都会在另一端变成一长串数据。

对于数据报或消息套接字,我明白为什么更清晰一点会有所帮助。但是看起来您只发送了一个数据报或消息与单个 sndmsg 调用;不是每个缓冲区元素一个。

实际上,出于好奇,我深入研究了 Linux 源代码,以便更好地了解这个答案。看起来 sendsendto 只是 Linux 中 sendmsg 的包装器,它们为您构建了 struct msghdr .事实上,UDP sendmsg 实现为每个 sendmsg 调用留出了一个 UDP header 的空间。

如果性能是您所担心的,那么如果您只传入一个 iovec,您似乎不会从 sendmsg 中受益。但是,如果您在用户空间中连接缓冲区,这可能会为您赢得一些。

它有点类似于writev,额外的好处是您可以指定目标地址以用于无连接套接字(如UDP)。如果您喜欢这种东西,您还可以添加辅助数据。 (通常用于跨 UNIX 域套接字发送文件描述符。)

关于c - sendmsg 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4258834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com