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

标签 c linux pipe

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

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

“其他应用程序”是一个闭源计算器(一个从标准输入读取 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/

相关文章:

c - C编程中的合并

c - 在curl_global_init调用上的SIGSEGV

linux - 如何修复 SBT 崩溃 : java. lang.NumberFormatException : For input string: "0x100"?

html - Angular 2将新项目添加到列表时,自定义管道不重新排序列表

windows - 如何使用管道将一个命令的输出重定向到另一个命令的输入?

c - c中的迭代目录遍历

c - 缓存大小对代码的影响

python - 使用 crontab 和 python 写入 file.txt

linux - meteor 安装失败 - 仅达到 45%

R 与点 (".")、 "~"和管道 (%>%) 运算符的组合