【发布时间】:2015-03-15 14:38:31
【问题描述】:
这段代码应该做的是:有parent.cpp和child.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);
【问题讨论】:
-
首先,您应该发布完整的代码。 (读者应该能够获取您编写的内容并对其进行编译,而无需添加 main 函数。)其次,您应该指出您实际得到的结果。您是否收到编译器错误或运行时错误?如果是这样,请发布它们。如果没有错误,你会得到什么结果?与您的预期有何不同?
标签: c++ pipe parent-child pid dup2