如何以正确的格式沿第二个管道发回数据?

时间:2017-08-14 00:56:00

标签: c++ process pipe parent-child

我一直在努力两天试图修复我的代码中的最后一个错误,但似乎无法找到错误。代码假定为(按顺序):

  1. 从用户处收到一个字符串(在本例中为我)
  2. 创建子流程
  3. 将字符串发送到子进程
  4. 重写字符串,以便每个单词都以大写字母开头
  5. 使用更改
  6. 将字符串发回给父级
  7. 显示字符串
  8. 代码运行正常,直到父阅读。示例输出是:

    输入:" hello tHerE"

    家长写了" hello tHerE"

    孩子读了" hello tHerE"

    孩子写道" Hello There"

    家长阅读@#$%^ $#%^& * - 或其他一些非标准字符,然后显示错误 -

    双重免费或腐败(外出):0x00007ffeeebb2690 ***

    以下是我的代码:

    #include <iostream>
    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    int main(){
        int fd[2];
        int pfc[2];
        int status = 0;
        string val = "";
    
        if(pipe(fd) == -1 || pipe(pfc) == -1) fprintf(stderr,"Pipe failed");
    
        pid_t pid = fork();
    
        // fork() returns 0 for child process, child-pid for parent process.
        if (pid == 0){   // child: reading only, so close the write-descriptor
            string writeval = "";
            close(fd[1]);
    
            // now read the data (will block)
            read(fd[0], &val, sizeof(val));
            cout << "Child reads " << val.c_str() << endl;
            string temp = " " + val;
            transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
            for(size_t i = 1; i < temp.length(); i++){
                if(!isspace(temp[i]) && isspace(temp[i-1])){
                    temp[i] = toupper(temp[i]);
                }
            }
            writeval = temp.substr(1, temp.length() - 1);
    
            // close the read-descriptor
            close(fd[0]);
            close(pfc[0]);
            cout << "Child writes " << writeval.c_str() << endl;
    
            write(pfc[1], &writeval, sizeof(writeval));
    
            close(pfc[1]);
            exit(0);
        }
        else{
            string readval = "";
            string temp ="";
            // parent: writing only, so close read-descriptor.
            close(fd[0]);
    
           // send the value on the write-descriptor.
            while(getline(cin, temp)){
                val += temp;
            }
            write(fd[1], &val, sizeof(val));
    
            cout << "Parent writes " << val << endl;
            // close the write descriptor
            close(fd[1]);
            //wait(&status);
            close(pfc[1]);
            read(pfc[0], &readval, sizeof(readval));
            cout << "Parent reads " << readval << endl;
            close(pfc[0]);
    
        }
        return 0;
    }
    

1 个答案:

答案 0 :(得分:0)

所以答案很简单。在子进程中,我将writeval的内存位置传递回父方法,但在父进程中我试图从readval的内存位置读取。通过将它们更改为if / else调用之外的相同变量来修复此问题,就像使用变量val一样。

有关此问题的详细信息,请参阅here