这个 dup2 和管道有什么问题
what is wrong with this dup2 and pipes?
这段代码应该做的是:有父.cpp和子.cpp。父级会将缓冲区中的任何内容发送给子级,子级将发回收到的任何内容给父级。我不知道我做错了什么。我很困惑父母缺少什么,以及我应该在孩子身上包含什么。
//parent.cpp
//Check for fork error
if ( (pid = fork()) < 0 )
{
cerr << "FORK ERROR" << endl;
return -3;
}
else if (pid == 0) // Child
{
close(fd1[1]);//Close parent's stdout-write
close(fd2[0]);//Close child's stdin-read
if (fd1[0] != STDIN_FILENO)//Make sure file desc. matches
{
if (dup2(fd1[0], STDIN_FILENO) != STDIN_FILENO)
{
cerr << "dup2 error to stdin" << endl;
}
close(fd1[0]);
}
if (fd2[1] != STDOUT_FILENO)//Make sure file desc. mathces
{
if (dup2(fd2[1], STDOUT_FILENO) != STDOUT_FILENO)
{
cerr << "dup2 error to stdout" << endl;
}
close(fd2[1]);
}
if ( execl("./child", "child", (char *)0) < 0 )
{
cerr << "system error" << endl;
return -4;
}
return 0;
}//end of child
else //parent
{
int rv;
close(fd1[0]);//Close parent's read
close(fd2[1]);//close child's write
if ( write(fd1[1], buffer, strlen(buffer)) != strlen(buffer))
{
cerr << "Write ERROR FROM PIPE" << endl;
}
if ( (rv = read(fd2[0], buffer, MAXLINE)) < 0 )
{
cerr << "READ ERROR FROM PIPE" << endl;
}
else if (rv == 0)
{
cerr << "Child Closed Pipe" << endl;
return 0;
}
cout << "Output of child is: " << buffer;
return 0;
}//end of parent
//child.cpp
char line[1000];
int MAXLEN=1001;
read(STDIN_FILENO, line, MAXLEN);
我的猜测是你的进程被阻止了。 将少量数据写入子项,子项将处理这些数据。 但是,子项不生成任何输出,但正在等待更多数据。 父母现在在等待孩子给它一些数据,孩子在等待父母,你有一个经典的死锁。 尝试在写入父项之后和read
之前关闭fd1[1]
。 孩子将意识到没有更多的数据,并将在终止之前产生输出。
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了