gpt4 book ai didi

C++双向管道 - 卡在循环中尝试从子进程读取

转载 作者:太空宇宙 更新时间:2023-11-04 13:07:40 24 4
gpt4 key购买 nike

我正在尝试制作一个双向管道,让一个parent 进程向一个child 进程发送消息并等待它的回答,对回答做一些事情然后发送另一条消息,并一遍又一遍地重复。
child 进程使用 STDIN 和 STDOUT 接收和发送输入,而 parent 将消息用作 c++ strings,因此在发送之前将它们转换收到后,不同的消息也有不同的(未知)长度。
我写了一个简单的代码来举例说明:

父级.cpp:

#include <unistd.h>
#include <iostream>
#include <cstring>
#include <string>

int main(){
int parent_to_child[2];
int child_to_parent[2];

pipe(parent_to_child);
pipe(child_to_parent);

int childPID = fork();

if(childPID == 0){
//this is child
close(parent_to_child[1]);//Close the writing end of the incoming pipe
close(child_to_parent[0]);//Close the reading end of the outgoing pipe

dup2(parent_to_child[0], STDIN_FILENO);//replace stdin with incoming pipe
dup2(child_to_parent[1], STDOUT_FILENO);//replace stdout with outgoing pipe

//exec child process
char filename[] = "child.out";
char *newargv[] = { NULL };
char *newenviron[] = { NULL };
execve(filename, newargv, newenviron);
}else{
//this is parent
close(parent_to_child[0]);//Close the reading end of the outgoing pipe.
close(child_to_parent[1]);//Close the writing side of the incoming pipe.

int parent_frame = 0;
char str_to_write[100];

char reading_buffer;
std::string received_str;

do{
//Make the frame number a cstring and append '\n'
strcpy(str_to_write, std::to_string(parent_frame).c_str());
strcat(str_to_write,"\n");

write(parent_to_child[1], str_to_write, strlen(str_to_write));
std::cout << "Parent sent: "<< str_to_write <<std::endl;


received_str = "";
while(read(child_to_parent[0], &reading_buffer, 1) > 0){
received_str += reading_buffer;
}

std::cout << "Parent received: "<< received_str<< std::endl;
} while (++parent_frame);
}
return 0;
}

Child.cpp

#include <unistd.h>
#include <iostream>

int main(){
int child_frame = 0;
char child_buffer[1024];
do{
std::cin >> child_buffer; //wait for father's messages
std::cout << "CHILD received: "<< child_buffer<<" at frame "<< child_frame<<"\n"; //return message to father
}while(++child_frame);

return 0;
}

执行父输出:

Parent sent: 0

...然后卡住了

如果我不创建从子级到父级 的管道并让父级写入 STDOUT,代码将按预期工作,因为我在终端中看到了子级的响应。因此,表明子级能够从父级读取,但由于某种原因,父级无法从子级读取。

所以我的问题是:为什么父级不能读取子级的输出,这是如何工作的?我做错了什么?

最佳答案

问题出在最里面的 while 循环中父级对 read(2) 的调用。

这会持续读取数据,直到 read(2) 返回一个值 <= 0。但这只会在 (1) 发生错误或 (2) child 关闭他们的写入端时发生管道。因此, child 发送了它的消息, parent 愉快地阅读了它,然后就坐在那里等待 child 的进一步数据。这显然永远不会到来。

问题是您在 while 循环中的条件。你不想读到 EOF 或错误,你想读整行(如果你使用换行符作为消息定界符)。查看 getline(3) 以使其更容易一些并避免一次读取单个字节,或者如果您将代码变形为更多 C++,则查看 std::getline风格。

关于C++双向管道 - 卡在循环中尝试从子进程读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41495219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com