![](/img/trans.png)
[英]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.