1
我一直在掙扎了兩天,試圖解決這一問題的最終錯誤在我的代碼,但似乎無法找到錯誤。該代碼是設於(按順序):如何以正確的格式將數據發送回沿第二管?
- 接收來自用戶的字符串(在這種情況下我)
- 創建子進程
- 發送串子進程
- 返修繩子,讓每一個字以大寫字母開頭
- 字符串發送回父與變化
- 顯示字符串
代碼,直到家長閱讀運行正常。一個例子輸出爲:
輸入: 「你好」
家長寫道: 「你好」
孩子在讀 「你好」
孩子寫道: 「你好」
父閱讀@#$%^ $#%^ & *或其他一些非標準字符,然後顯示錯誤 -
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;
}