c - 如何将标准输入从 child 传输到 parent ?

标签 c pipe stdin

我正在尝试从父进程exec()子进程。在这个子进程中,我要求用户输入一条消息,以便父​​进程可以将其打印出来,但我找不到方法......

到目前为止,我的代码是:

parent.c

int main(int argc, char **argv) {
    int fd[2];
    char line[80];

    pipe(fd);

    pid_t pid = (pid_t)fork();

    if(pid > 0) {
        waitpid(pid, NULL, 0);
        close(fd[0]);
        int size = read(fd[1], line, 79);
        close(fd[1]);
        line[size] = '\0';
        printf("[parent] Received \"%s\", size = %d\n", line, size);
    }
    else {
        close(fd[1]);
        close(stdin);
        dup2(fd[0], stdin);
        close(fd[0]);
        exec("./child", 0, NULL);
    }

    return 0;
}

child.c

int main(int argc, char **argv) {
    char line[80];

    printf("[child] Enter message: ");
    gets(line, 80);
    printf("[child] line = %s\n", line);

    return 0;
}

当我启动父进程时,它会显示[child] Enter message:,但是当我尝试输入内容时,即使按下返回键,也不会出现任何内容。

你知道我怎样才能让它发挥作用吗?

感谢您的帮助。

最佳答案

除了我评论中提到的问题之外,您遇到的问题是死锁。这是因为父进程等待子进程退出。但子进程正在等待永远不会到达的输入。

那是因为在子进程中你说输入应该来自管道

此外,在父进程中,您尝试从管道的写入端读取

最后,只要子进程想要读取用户输入,您的程序就永远无法工作,因为所有用户输入都将进入进程。

为了使其一切正常,您需要重新考虑您的设计,并使父进程成为读取用户输入并写入管道的进程。子进程应该从管道读取并打印到(非管道)标准输出。或者您关闭父级中的(正常的、非管道的)标准输入,并在子级中写入管道(作为标准输出)。

关于c - 如何将标准输入从 child 传输到 parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40768381/

相关文章:

node.js - 如何从 node.js 写入 System.in?

python - 使用 raw_input 会导致 PyQt 页面加载出现问题

go - 如何从标准输入中按字节读取?

c - "(void)temp;"语句是什么意思?

python - ffmpeg stdin 管道搜索

ruby - 如果父 ruby​​ 脚本被终止,则由 IO.popen 自动终止进程

多个子级之间的 C++ 管道

c - 使用 SimpleScalar 运行基本代码时出错

c - 打乱一个 float ?

c - scanf() 将换行符保留在缓冲区中