practical examples use dup or dup2

前端 未结 5 1476
滥情空心
滥情空心 2020-11-29 16:49

I know what dup / dup2 does, but I have no idea when it would be used.

Any practical examples?

Thanks.

5条回答
  •  离开以前
    2020-11-29 17:21

    One practical example is redirecting output messages to some other stream like some log file. Here is a sample code for I/O redirection.
    Please refer to original post here

    #include 
    
    main()
    {
        int    fd;
        fpos_t pos;
    
        printf("stdout, ");
    
        fflush(stdout);
        fgetpos(stdout, &pos);
        fd = dup(fileno(stdout));
        freopen("stdout.out", "w", stdout);
    
        f();
    
        fflush(stdout);
        dup2(fd, fileno(stdout));
        close(fd);
        clearerr(stdout);
        fsetpos(stdout, &pos);        /* for C9X */
    
        printf("stdout again\n");
    }
    
    f()
    {
    printf("stdout in f()");
    }
    

提交回复
热议问题