码迷,mamicode.com
首页 > 其他好文 > 详细

read_fd函数

时间:2019-04-25 14:36:13      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:socket   pre   byte   ...   script   bytes   name   lse   dde   

#include    <stdio.h>

#include    <stddef.h>
#include    <sys/socket.h>

void err_sys(const char *, ...);
void err_quit(const char *, ...);

ssize_t read_fd(int fd, void *ptr, size_t nbytes, int *recvfd)
{
    struct msghdr    msg;
    struct iovec    iov[1];
    ssize_t            n;

    union {
      struct cmsghdr    cm;
      char     control[CMSG_SPACE(sizeof(int))];
    } control_un;
    struct cmsghdr    *cmptr;

    msg.msg_control = control_un.control;
    msg.msg_controllen = sizeof(control_un.control);

    msg.msg_name = NULL;
    msg.msg_namelen = 0;

    iov[0].iov_base = ptr;
    iov[0].iov_len = nbytes;
    msg.msg_iov = iov;
    msg.msg_iovlen = 1;

    if ( (n = recvmsg(fd, &msg, 0)) <= 0) {
        return (n);
    }

    if ( (cmptr = CMSG_FIRSTHDR(&msg)) != NULL &&
        cmptr->cmsg_len == CMSG_LEN(sizeof(int))) {
        if (cmptr->cmsg_level != SOL_SOCKET) {
            err_quit("control level != SOL_SOCKET");
        }
        if (cmptr->cmsg_type != SCM_RIGHTS) {
            err_quit("control type != SCM_RIGHTS");
        }
        *recvfd = *((int *) CMSG_DATA(cmptr));
    } else {
        *recvfd = -1; /* descriptor was not passed */
    }

    return(n);
}

ssize_t Read_fd(int fd, void *ptr, size_t nbytes, int *recvfd)
{
    ssize_t        n;

    if ( (n = read_fd(fd, ptr, nbytes, recvfd)) < 0) {
        err_sys("read_fd error");
    }

    return (n);
}

 

read_fd函数

标签:socket   pre   byte   ...   script   bytes   name   lse   dde   

原文地址:https://www.cnblogs.com/soldierback/p/10768100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!