redhat linux 8.0下的传送文件描述符的问题

bingo_zb 2003-04-09 07:40:39
为什么子进程收不到呢???

#include "ourhdr.h"

int main(void)
{
int fdpipe[2], fd, n;
pid_t pid;
char line[MAXLINE];
struct msghdr msg;
struct iovec iov[1];
char cmsg[CMSG_SPACE(sizeof(int))];
struct cmsghdr *cmptr;

memset(&msg, 0, sizeof(msg));
memset(cmsg, 0, sizeof(cmsg));
msg.msg_control = cmsg;
msg.msg_controllen = sizeof(cmsg);

if(socketpair(AF_UNIX, SOCK_STREAM, 0, fdpipe) < 0)
err_sys("socketpair error");

if((pid = fork()) < 0)
err_sys("fork error");
else if(pid > 0)
{
close(fdpipe[0]);
if((fd = open("transfd.tmp", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
err_sys("parent: open error");
if(write(fd, "hello world!\n", 13) != 13)
err_sys("parent: write error");
lseek(fd, 0, SEEK_SET);

cmptr = CMSG_FIRSTHDR(&msg);
cmptr->cmsg_level = SOL_SOCKET;
cmptr->cmsg_type = SCM_RIGHTS;
cmptr->cmsg_len = CMSG_LEN(sizeof(int));
*(int *)CMSG_DATA(cmptr) = fd;
if(sendmsg(fdpipe[1], &msg, 0) != 0)
err_sys("parent: sendmsg error");
close(fd);
close(fdpipe[1]);

if(waitpid(pid, NULL, 0) != pid)
err_sys("parent: waitpid error");
}
else
{
close(fdpipe[1]);
iov[0].iov_base = line;
iov[0].iov_len = sizeof(line);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
if(recvmsg(fdpipe[0], &msg, 0) != 0)
err_sys("child: recvmsg error");
printf("child: len = %d\n", msg.msg_controllen);
if((cmptr = CMSG_FIRSTHDR(&msg)) == NULL || cmptr->cmsg_len != CMSG_LEN(sizeof(int)))
err_quit("child: not received fd");
cmptr = CMSG_FIRSTHDR(&msg);
fd = *(int *)CMSG_DATA(cmptr);

while((n = read(fd, line, MAXLINE)) > 0)
{
if(write(STDOUT_FILENO, line, n) != n)
err_sys("child: write error");
}
}

exit(0);
}


...全文
89 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangf023 2003-04-12
  • 打赏
  • 举报
回复
各位大哥大姐、博士硕士、工程师:我是一名应届毕业生,要做毕业设计,题目是“linux的文件系统,要求ext2带有日志功能”。本人能力有限,现请教各位具体方案
bingo_zb 2003-04-09
  • 打赏
  • 举报
回复
大侠帮帮忙啊

23,118

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧