如何解决从/向管道标准输入、标准输出读取和写入
我需要在 2 个不同的进程之间传递信息,我尝试使用管道来做到这一点。由于我从未使用过它们,因此我尝试从基础开始。但是,我似乎无法从子进程中读取信息并将其写回。
我有以下代码:
int main()
{
int in,out;
popen2("./Reader/reader",&in,&out);
int result = write(in,"hello",sizeof("hello"));
char out_arr[100];
result = read(out,out_arr,sizeof("Received"));
fprintf( stderr,"%s\n",out_arr);
return 0;
}
其中popen2如下:
#define READ 0
#define WRITE 1
pid_t
popen2(const char *command,int *infp,int *outfp)
{
int p_stdin[2],p_stdout[2];
pid_t pid;
if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0)
return -1;
pid = fork();
if (pid < 0)
return pid;
else if (pid == 0)
{
close(p_stdin[WRITE]);
dup2(p_stdin[READ],READ);
close(p_stdout[READ]);
dup2(p_stdout[WRITE],WRITE);
execl("/bin/bash","bash","-c",command,NULL);
perror("execl");
exit(1);
}
if (infp == NULL)
close(p_stdin[WRITE]);
else
{
*infp = p_stdin[WRITE];
}
if (outfp == NULL)
close(p_stdout[READ]);
else
{
*outfp = p_stdout[READ];
}
return pid;
}
这会打开一个子进程。如何从子进程读取我在主进程中写入管道的“你好”?如何写回主进程?
目前这似乎不起作用:
int main()
{
std::string input;
while(std::cin>>input)
{
std::cout<<"Received";
}
return 0;
}
解决方法
已解决
我错过了发送的字符数组末尾的 \n\r 以便从子进程中变为红色。
int main()
{
int in,out;
popen2("./Reader/reader",&in,&out);
int result = write(in,"hello\n\r",sizeof("hello\n\r"));
char out_arr[100];
result = read(out,out_arr,sizeof("Received"));
fprintf( stderr,"%s\n",out_arr);
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。