2017-08-14 19 views
1

我一直在挣扎了两天,试图解决这一问题的最终错误在我的代码,但似乎无法找到错误。该代码是设于(按顺序):如何以正确的格式将数据发送回沿第二管?

  1. 接收来自用户的字符串(在这种情况下我)
  2. 创建子进程
  3. 发送串子进程
  4. 返修绳子,让每一个字以大写字母开头
  5. 字符串发送回父与变化
  6. 显示字符串

代码,直到家长阅读运行正常。一个例子输出为:

输入: “你好”

家长写道: “你好”

孩子在读 “你好”

孩子写道: “你好”

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

double free or cor ruption(出):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; 
} 

回答

0

所以答案很简单。在子过程中,我是路过writeval的存储位置,在写回父类的方法,但在父过程中,我试图从readval的内存位置读取。这是通过改变他们是相同的变量中,如果/其他电话之外,就像是用变量val进行固定。

关于为什么这是一个问题的详细信息,请参阅here

相关问题