gpt4 book ai didi

c - 重定向 stdin 和 stdout in child in c

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:49 25 4
gpt4 key购买 nike

我需要创建一个客户端-服务器应用程序(使用套接字),基本思路是:

  • 客户端发送字符串
  • 服务器接收字符串并将其作为另一个应用程序的标准输入发送
  • 服务器读取应用程序的标准输出
  • 服务器向客户端发送应答。

“其他应用程序”是一个闭源计算器(一个从标准输入读取 4 5 + 并打印 9 的计算器)。

我试图在服务器上创建一个双管道,fork,并使用这个管道重定向计算的标准输入和标准输出:

if(!fork())
{

close(STDOUT_FILENO);
close(STDIN_FILENO);

dup2(outfd[0], STDIN_FILENO);
dup2(infd[1], STDOUT_FILENO);

close(outfd[0]); /* Not required for the child */
close(outfd[1]);
close(infd[0]);
close(infd[1]);

system("./calc/calc ");
exit(0);
}

服务器在一个管道上写入,在另一个管道上读取

    close(outfd[0]); /* These are being used by the child */
close(infd[1]);

char c;
do
{
c=getchar();
write(outfd[1],&c,1);
}while(c!='\n');
input[read(infd[0],input,100)] = 0; /* Read from child’s stdout */

printf("%s",input);

close(outfd[1]);
close(infd[0]);

我知道这很不完整,但我认为它至少应该在 calc 中打印第一行的输出。

(完整代码)

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{

int outfd[2];
int infd[2];

pipe(outfd); /* Where the parent is going to write to */
pipe(infd); /* From where parent is going to read */

if(!fork())
{

close(STDOUT_FILENO);
close(STDIN_FILENO);

dup2(outfd[0], STDIN_FILENO);
dup2(infd[1], STDOUT_FILENO);

close(outfd[0]); /* Not required for the child */
close(outfd[1]);
close(infd[0]);
close(infd[1]);

//system("/usr/bin/bc -q");
system("./calc/calc ");
exit(0);
}
else
{

char input[100];

close(outfd[0]); /* These are being used by the child */
close(infd[1]);

//write(outfd[1],"2^32\n",5); /* Write to child’s stdin */
//write(outfd[1],"2 4 +\n",6);
char c;
do
{
c=getchar();
write(outfd[1],&c,1);
}while(c!='\n');
input[read(infd[0],input,100)] = 0; /* Read from child’s stdout */

printf("%s",input);

close(outfd[1]);
close(infd[0]);

}
return 0;

它非常基础,但仅用于测试。当我执行它时,它什么也不做。

如果我 ps -e | grep calc 在执行期间,我可以看到它正在运行,但无论我输入什么似乎都没有做任何事情。

最佳答案

尝试移动:

close(outfd[1]);

do-while 循环和 input[read(infd[0],input,100)] = 0; 之间。

这将在 calc 的标准输入上发送 EOF。它会退出,这会刷新它的输出缓冲区,所以会有一些东西可以读取。

您的代码陷入僵局:您在关闭管道之前等待输出,但它在发送输出之前等待您关闭管道。

关于c - 重定向 stdin 和 stdout in child in c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27736042/

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