簡體   English   中英

Unix C - 將stdout重定向到管道然后再返回到stdout

[英]Unix C - Redirecting stdout to pipe and then back to stdout

我不確定是否可以執行以下操作,因為我無法通過Google找到任何問題/結果。 我想將fork()的stdout更改為管道,然后將其更改回正常的stdout。

這就是我所擁有的:

FirstExecutable:

int main()
{
      int fd[2]; //Used for pipe
      int processID;

      if(pipe(fd) == -1)
      {
            printf("Error - Pipe error.\n");
            exit(EXIT_FAILURE);
      }

      if((processID = fork()) == -1)
      {
            fprintf(stderr, "fork failure");
            exit(EXIT_FAILURE);
      }

      if(processID == 0)
      {
           int newFD = dup(STDOUT_FILENO);

          char newFileDescriptor[2];

          sprintf(newFileDescriptor, "%d", newFD);

          dup2 (fd[1], STDOUT_FILENO);

          close(fd[0]);

          execl("./helloworld", "helloworld", newFileDescriptor, NULL);
      }
      else
      { 
          close(fd[1]);

          char c[10];

          int r = read(fd[0],c, sizeof(char) * 10);

          if(r > 0)
               printf("PIPE INPUT = %s", c);
      }
}

你好,世界

int main(int argc, char **argv)
{
      int oldFD = atoi(argv[1]);

      printf("hello\n"); //This should go to pipe

      dup2(oldFD, STDOUT_FILENO);

      printf("world\n"); //This should go to stdout
}

期望的輸出:

world
PIPE OUTPUT = hello

實際產量:

hello
world

嘗試改變

  printf("hello\n");

  printf("hello\n");
  fflush(stdout);

這里的問題是緩沖。 出於效率原因,FILE句柄在寫入時並不總是立即產生輸出。 相反,他們在內部緩沖區中累積文本。

有三種緩沖模式,無緩沖,線緩沖和塊緩沖。 無緩沖的句柄總是立即寫入(stderr是無緩沖的)。 行緩沖句柄等到緩沖區已滿或打印換行符( '\\n' )(如果stdout引用終端,則stdout為行緩沖)。 塊緩沖句柄一直等到緩沖區已滿(如果stdout沒有引用終端,則stdout是塊緩沖的)。

當你的helloworld程序啟動時,stdout會進入管道,而不是終端,所以它被設置為塊緩沖。 因此,printf調用只是將文本存儲在內存中。 由於緩沖區未滿,因此僅在stdout關閉時才刷新,在這種情況下會在程序退出時發生。

但是當程序退出時,文件描述符1(stdout)已經恢復,以引用父項的原始標准輸出,而不是管道。 因此,緩沖的輸出最終被寫入原始標准輸出。

fflush強制立即寫入緩沖的文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM