c - fork 进程的子进程中的标准输入/输出/错误重定向

标签 c bash io-redirection fork

我正在用 C 编写一个基本的反向 shell:

if(-1 ==  (myShell->pid = fork()))
{
    PipeSet_close(&myShell->pipeSet);
    return RS_ERROR;
}

if(myShell->pid == 0)
{
    /* close pipe ends child doesn't need */
    close(myShell->pipeSet.stdInPipe[1]);
    close(myShell->pipeSet.stdOutPipe[0]);
    close(myShell->pipeSet.stdErrPipe[0]);

    /* dupe 2 the pipes we DO need frm their originals */
    dup2(myShell->pipeSet.stdInPipe[0], fileno(stdin));
    dup2(myShell->pipeSet.stdOutPipe[1],fileno(stdout));
    dup2(myShell->pipeSet.stdErrPipe[1],fileno(stderr));

    /* bash now replaces child process. only returns after bash terminates */
    execl(getenv("SHELL"),NULL,NULL);
    return RS_SUCCESS;
}

我可以使用我的父进程从我的 3 个管道中读取和写入。这允许我通过 child 执行基本的 shell 命令。 ls -l、ps、chmod +x 等。我遇到的问题是当我使用 shell 运行一个需要用户输入的简单程序时。我使用以下程序对此进行测试:

int main()
{
int opt;
while (1==1)
{
    printf("-----Remote Shell Menu test:------\n");
    printf("   1. print 1\n");
    printf("   2. print 2\n");
    printf("   3. exit\n");
    fflush(stdin);
    scanf("%d",&opt);

    switch (opt)
    {
    case 1: printf("Pressed 1\n"); break;
    case 2: printf("Pressed 2\n"); break;
    case 3: return 0;
    default: printf("unknown menu option %d\n",opt);
    }
}
}

我可以像往常一样通过我的反向 shell 与这个子程序交互,然后按“1”“2”1“3”但是我没有得到菜单或看到任何输出我的 stdout 管道,直到整个菜单程序终止,然后我按 3。谁能告诉我这是为什么?

如果从我的 fork bash 中生成另一个 bash shell,情况就不是这样了......

最佳答案

您有 fflush(stdin) 什么都不做。 fflush 仅用于输出流。我相信如果您将其更改为 fflush(stdout),它将解决您的缓冲问题。

关于c - fork 进程的子进程中的标准输入/输出/错误重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15165686/

相关文章:

比较预处理器宏是否相等

c - 将字符串分配给C中结构中的元素

bash - 如何将多个命令的输出重定向到一个文件?

shell - "<inp somecommand"和 "somecommand <inp"和有什么区别?

bash - 将 stdout 和 stderr 都重定向到文件,仅打印 stdout

c - 如何在不提示用户的情况下检测 Linux C GUI 程序中的按键?

c - 将指针移交给 C 中的另一个函数

linux - 需要帮助在 Linux 终端中使用 sed 编辑多个文件

linux - 如何在 bash 脚本中使用 grep 命令来搜索一行,但只打印该行的某些部分,并特别排除该单词本身?

linux - 是否可以在Linux命令行中使用 "py"代替 "python"?