C++ 如何以正确的格式沿第二条管道发回数据?
我花了两天时间试图修复代码中的最后一个错误,但似乎找不到错误。该代码假定为(按顺序):C++ 如何以正确的格式沿第二条管道发回数据?,c++,process,pipe,parent-child,C++,Process,Pipe,Parent Child,我花了两天时间试图修复代码中的最后一个错误,但似乎找不到错误。该代码假定为(按顺序): 从用户(在本例中为me)接收字符串 创建子进程 将字符串发送到子进程 修改字符串,使每个单词都以大写字母开头 将字符串连同更改一起发送回父级 显示字符串 在父级读取之前,代码可以正常运行。一个示例输出是: 输入:“你好” 家长写“你好” 孩子读着“你好” 孩子写“你好” 父级读取@#$%^$#%^&*-或某些其他此类非标准字符,然后显示错误- 双重自由或损坏(out):0x00007FFEEBB2690***
#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
int-fd[2];
int-pfc[2];
int status=0;
字符串val=”“;
如果(管道(fd)=-1 | |管道(pfc)=-1)fprintf(标准,“管道故障”);
pid_t pid=fork();
//fork()为子进程返回0,为父进程返回子pid。
如果(pid==0){//child:reading only,那么关闭写描述符
字符串writeval=“”;
关闭(fd[1]);
//现在读取数据(将阻塞)
读取(fd[0],&val,sizeof(val));
cout因此答案很简单。在子进程中,我将writeval在write back中的内存位置传递给父方法,但在父进程中,我尝试从readval的内存位置读取。这是通过将它们更改为相同的变量来解决的,在if/else调用之外,就像使用变量val一样。
有关这是一个问题的原因的更多详细信息,请参阅。因此答案很简单。在子进程中,我将writeval的内存位置在write back中传递给父方法,但在父进程中,我尝试从readval的内存位置读取。这是通过将它们更改为相同的变量来解决的,在if/e之外lse调用,如使用变量val完成的调用
有关此问题原因的更多详细信息,请参阅