繁体   English   中英

在POSIX C中将stdout重定向到stdin

[英]Redirecting stdout to stdin in POSIX C

我正在尝试编写一个将stdout重定向到stdin的程序,主要是为了更好地了解dup2()工作方式。 我尝试编写一个简单的程序来制作它,这样,如果您将printf()某些操作,以后就可以将它scanf()scanf() ,但是却无法使其正常工作。 首先,我尝试仅使用dup2(0, 1) ,认为它会将stdout (1)重定向到stdin (0)。 这没用。 我以为,由于一个用于输入而另一个用于输出,它们可能不兼容,所以我尝试使用管道来执行此操作,如下所示:

#include <stdio.h>
#include <unistd.h>
int main() {
    int pipe_desc[2];
    pipe(pipe_desc);
    dup2(pipe_desc[0], 0);
    dup2(pipe_desc[1], 1);
    printf("foo");
    char bar[20];
    scanf("%s", bar);
    fprintf(stderr, "%s", bar);
}

然而,现在即使printf ,按照我的理解,应该把"foo"到管道中,当我打电话scanf ,程序只是挂在那里,也不从标准输入,也没有从管道中读取。 怎么了? 这段代码究竟发生了什么? 是否可以在没有管道(或与此有关的任何其他辅助结构)的情况下完成这种重定向?

您的工作方式,代码中有解释。

#include <stdio.h>
#include <unistd.h>
int main() {
        int pipe_desc[2];
        pipe(pipe_desc);
        printf("pid = %d \n",getpid());
        /* above statement creates 2 descriptors 3 & 4. 3 is for read and 4 is for write**/
        dup2(pipe_desc[0], 0);
        /** 3 is duplicates with 0(stdin) i.e if you try to do scanf, it won't scan from keyboard, it will scan from pipe(read end, for that make sure something should be there in pipe  **/
        dup2(pipe_desc[1], 1);
        /** 4 is duplicates with 1 (stdout) i.e if you try to write onto screen, it won't. It will try into pipe write end **/
        /** SO TILL NOW FD DETAILS
                0,3 --> PIPE_DESC[0]
                1,4 --> PIPE_DESC[1] 
        **/
        #if 1
        fflush(stdout);
        printf("foo\n");//it won't print 
        char bar[20];
        scanf("%s", bar);//it won't scan bcz 0 is poiting to pipe_desc[0]
        #endif
        /** YOU CAN CHECK USING OTHER TERMINAL "ls -l /proc/pid/fd/" **/

        fprintf(stderr, "%s", bar);// fd 2 is still available.So foo gets printed on screen
}

在上面的程序运行时打开另一个终端,使用

root@xyz-PC:/home/achal/s_flow/cpp# ls -l /proc/4503/fd
total 0
lr-x------ 1 root root 64 Jan 15 16:45 0 -> pipe:[782489]
l-wx------ 1 root root 64 Jan 15 16:45 1 -> pipe:[782489]
lrwx------ 1 root root 64 Jan 15 16:45 2 -> /dev/pts/9
lr-x------ 1 root root 64 Jan 15 16:45 3 -> pipe:[782489]
l-wx------ 1 root root 64 Jan 15 16:45 4 -> pipe:[782489]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM