2017-08-14 1 views
1

私はコードでこの最終的なバグを修正するために2日間苦労していますが、エラーを見つけることはできません。2番目のパイプに沿って正しい形式でデータを送り返すにはどうすればよいですか?

  1. は、ユーザから文字列を受信
  2. リワーク子プロセスに文字列を送信し、子プロセス
  3. を作成します(この場合、私の中で):コードは(順番に)想定するのです文字列は、なるように、すべての単語が
  4. が変化して親に戻っ
  5. 表示する文字列を文字列を送る大文字で始まる

親が読み取るまで、コードは正常に実行されます。出力例は次のとおりです。

入力: "こんにちは"

親に書き込む "こんにちは"

子供読み込む "こんにちは"

子供が "こんにちは"

親を書き込み@#$%^ $#%^ & * - その他の非標準文字を読み取った後、エラーを表示する -

ダブルフリーまたはコール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で行われたように、if/else呼び出しの外で同じ変数に変更することで修正されています。

これがなぜ問題なのかについては、hereを参照してください。

関連する問題