这个 dup2 和管道有什么问题

what is wrong with this dup2 and pipes?

本文关键字:什么 问题 管道 dup2 这个      更新时间:2023-10-16

这段代码应该做的是:有父.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]。 孩子将意识到没有更多的数据,并将在终止之前产生输出。