【问题标题】:what is wrong with this dup2 and pipes?这个 dup2 和管道有什么问题?
【发布时间】: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


【解决方案1】:

我的猜测是您的进程被阻止了。您将少量数据写入子进程,由子进程处理。然而,孩子没有输出,但正在等待更多数据。父级现在正在等待子级给它一些数据,而子级正在等待父级,而你有一个经典的死锁。尝试在父项中写入之后和read 之前关闭fd1[1]。孩子会意识到没有更多的数据,并会在终止之前产生输出。

【讨论】:

    猜你喜欢
    • 2012-02-20
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    相关资源
    最近更新 更多