【问题标题】:Connecting stdout to stdin of the same process in Linux在Linux中将stdout连接到同一进程的stdin
【发布时间】:2018-06-20 04:09:31
【问题描述】:

我正在编写一个(ab)使用 APL 引擎 libapl.so 的应用程序。该库包含一种允许我捕获结果的机制,但它会将一些内容转储到 stdout 和 stderr。所以我的问题是,有没有办法捕获写入标准输出的东西,而不是让它进入屏幕,通过管道传输到另一个进程,或者诸如此类?例如,有没有办法将标准输出连接到同一进程的标准输入?我在 GTK+/Glib 中修改了 pipe2()、dup(2) 和各种奇怪的东西,但我还没有找到正确的咒语。

【问题讨论】:

    标签: stdout stdin capture


    【解决方案1】:

    做了更多的戳——至少一个解决方案似乎是创建一个fifo,open() 两次,一次用于读取,一次用于写入,然后dup2() 将写入fd 写入stdout fd。这会导致通过 fifo 管道写入标准输出,应用程序可以在该管道中读取它。 (感谢大约 7 年前一个名叫 Hasturkun 的人的启发。)

    这是一段演示代码:

    #include <fcntl.h>
    #include <errno.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    
    int
    main (int ac, char *av[])
    {
      char tname[64];
      sprintf (tname, "/tmp/testpipe%d", (int)getpid ());
      int rc = mkfifo (tname, 0666);
      if (rc != 0) {
        perror ("Creating fifo");
        return 1;
      }
    
      int temp_in_fd  = open (tname, O_NONBLOCK | O_RDONLY);
      if (temp_in_fd < 0) {
        perror ("Opening new input");
        return 1;
      }
      int temp_out_fd = open (tname, O_NONBLOCK | O_WRONLY);
      if (temp_out_fd < 0) {
        perror ("Opening new output");
        return 1;
      }
    
      FILE *temp_in  = fdopen (temp_in_fd,  "r");
      if (!temp_in) {
        perror ("Creating new input FILE");
        return 1;
      }
      FILE *temp_out = fdopen (temp_out_fd, "w");
      if (!temp_out) {
        perror ("Creating new input FILE");
        return 1;
      }
    
      dup2 (fileno (temp_out), STDOUT_FILENO);
    
      printf("Woot!");
      fflush(stdout);
    
    #define BFR_SIZE        64
      char bfr[BFR_SIZE];
      ssize_t sz = fread (bfr, 1, BFR_SIZE, temp_in);
      fprintf (stderr, "got %d bytes: \"%s\"\n", (int)sz, bfr);
    
      fclose (temp_out);
      fclose (temp_in);
      unlink (tname);
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 2022-11-25
      相关资源
      最近更新 更多