问题描述
我需要创建一个客户端服务器应用程序(使用套接字),其基本思想是:
I need to create a client-server app (using sockets), the basic idea is:
- 客户端发送字符串
- 服务器接收字符串并将其作为另一个应用程序的stdin发送
- 服务器读取应用程序的标准输出
- 服务器将答案发送给客户端.
其他应用"是一个封闭源calc(一个从stdin读取4 5 +
并打印9
的计算器).
The "other app" is a closed source calc (a calculator which reads from stdin the sort of 4 5 +
and prints 9
).
我正在尝试在服务器上创建一个双管道,分叉,并使用此管道重定向calc的stdin和stdout:
I'm trying to create a double pipe on the server, fork, and use this pipes to redirect stdin and stdout of the calc:
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);
}
从服务器上写一个管道,然后再读另一个管道
and from the server write on one pipe and read the other
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中打印第一行的输出.
I know this is very incomplete, but I think it should at least print the output of the first line in 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;
这是非常基础的,但仅用于测试.当我执行它时,它什么也没做.
It's very basic, but it's just for testing. When I execute it, it does nothing.
如果我在执行过程中ps -e | grep calc
,我可以看到它正在运行,但是我输入的内容似乎无济于事.
If I ps -e | grep calc
during the execution, I can see it is running, but whatever I type doesn't seems to do anything.
推荐答案
尝试移动:
close(outfd[1]);
在do-while
循环和input[read(infd[0],input,100)] = 0;
之间.
这将在calc
的标准输入上发送EOF
.它将退出,这将刷新其输出缓冲区,因此将需要读取一些内容.
This will send EOF
on calc
's stdin. It will exit, and this will flush its output buffer, so there will be something to read.
您的代码陷入僵局:在关闭管道之前,您正在等待输出,但是在管道发送输出之前,它正在等待您关闭管道.
Your code is deadlocked: you're waiting for output before you close the pipe, but it's waiting for you to close the pipe before it sends output.
这篇关于在C语言的孩子中重定向stdin和stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!