C language. Read from stdout

前端 未结 4 1919
抹茶落季
抹茶落季 2021-01-03 01:30

I have some troubles with a library function. I have to write some C code that uses a library function which prints on the screen its internal steps. I am not interested to

4条回答
  •  情深已故
    2021-01-03 01:43

    An expanded version of the previous answer, without using files, and capturing stdout in a pipe, instead:

    #include 
    #include 
    
    main()
    {
       int  stdout_bk; //is fd for stdout backup
    
       printf("this is before redirection\n");
       stdout_bk = dup(fileno(stdout));
    
       int pipefd[2];
       pipe2(pipefd, 0); // O_NONBLOCK);
    
       // What used to be stdout will now go to the pipe.
       dup2(pipefd[1], fileno(stdout));
    
       printf("this is printed much later!\n");
       fflush(stdout);//flushall();
       write(pipefd[1], "good-bye", 9); // null-terminated string!
       close(pipefd[1]);
    
       dup2(stdout_bk, fileno(stdout));//restore
       printf("this is now\n");
    
       char buf[101];
       read(pipefd[0], buf, 100); 
       printf("got this from the pipe >>>%s<<<\n", buf);
    }
    

    Generates the following output:

    this is before redirection
    this is now
    got this from the pipe >>>this is printed much later!
    good-bye<<<
    

提交回复
热议问题