linux提供的sendmsg接口主要是为了满足哪种类型的需求

passing file descriptor to another process.
■网友
因为进程间传递文件描述符不能直接用传递数字的方法。所以需要sendmsg
■网友
【linux提供的sendmsg接口主要是为了满足哪种类型的需求】 我们项目中用sendmsg有一种玩法还不错,就是我们的协议包,包头可能要包几层的情况,用sendmsg会很方便。
ssize_t sendmsg(int sockfd, 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 */ size_t msg_controllen; /* ancillary data buffer len */ int msg_flags; /* flags (unused) */};重点就在msg_iov了
struct iovec iov = {\t{.iov_base=(void*)proxy_hdr, .iov_len= IPC_HEADER_SZ}, {.iov_base=(void*)\u0026amp;trans_hdr, .iov_len= TRANMIT_HEADER_SZ},\t{.iov_base=(void*)buf, .iov_len=len }};这里我们发送的数据是buf,然后我们会在buf前面封装两层包头,一个是proxy_hdr,一个是trans_hdr,直接调用一次sendmsg就完成了。
如果使用send直接发送的话,正常流程是定义一个buffer,先memcpy把proxy_hdr放进buffer,再memcpy把trans_hdr放进buffer,然后把buf的数据放进buffer,最后调用send发送buffer,总结起来就是3次memcpy加一次send,比起一次sendmsg多了3次系统调用。


    推荐阅读