进程间传递描述符代码参考

以下是传递描述符的大致代码,供参考:

#include<sys/types.h> #include <sys/sockets.h> #include <sys/uio.h> #include <error.h> #include <stddef.h> int send_fd(int clifd, int fd) { struct iovec iov[1]; struct msghdr msg; char buf[2]; iov[0].iov_base = buf; iov[0].iov_len = 2; msg.msg_iov = iov; msg.msg_iovlen = 1; msg.msg_name = NULL; msg.msg_namelen = 0; if(fd < 0) { msg.msg_accrights = NULL; msg.msg_accrightslen = 0; buf[1] = -fd; if(0 == buf[1]) buf[1] = 1; } else { msg.msg_accrights = (caddr_t)&fd; msg.msg_accrightslen = sizeof(int); buf[1] = 0; } buf[0] = 0; if(sendmsg(clifd, &msg, 0) != 2) return -1; return 0; } int recv_fd(int servfd, ssize_t (*userfunc)(int, const void*, size_t)) { int newfd, nread, status; char *ptr, buf[MAXLINE]; struct iovec iov[1]; struct msghdr msg; status = -1; for( ; ; ) { iov[0].iov_base = buf; iov[0].iov_len = sizeof(buf); msg.msg_iov = iov; msg.msg_iovlen = 1; msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_accrights = (caddr_t)&newfd; msg.msg_accrightslen = sizeof(int); if((nread = recvmsg(servfd, &msg, 0)) < 0) error("recvmsg error"); else if(0 == nread) { error("connection closed by server"); return -1; } for(ptr = buf; ptr<&buf[nread]; ) { if(0 == *ptr++) { if(ptr != &buf[nread-1]) error("message format error"); status = *ptr & 255; if(0 == status) { if(msg.msg_accrightslen != sizeof(int)) err_dump("status = 0 but no fd"); } else newfd = -status; nread -= 2; } } if(nread > 0) if((*userfunc)(STDERR_FILENO, buf, nread) != nread) return(-1); if(staus >= 0) return newfd; }

你可能感兴趣的:(struct,server,null)