[英]how to run an application in c++ and write to its stdin and read from its stdout in windows
[英]Read and write from/to piped stdin,stdout
我需要在两个不同的进程之间传递信息,我尝试使用管道来做到这一点。 由于我从未使用过它们,我试图从基础开始。 但是,我似乎无法从子进程中读取信息并将其写回。
我有以下代码:
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;
}
这会打开一个子进程。 如何从子进程读取主进程中写入 pipe 的“你好”? 我怎样才能写回主进程?
目前这似乎不起作用:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.