Unix-C - Umleiten von stdout an Rohr und dann wieder auf stdout

Ich bin mir nicht sicher, ob das folgende getan werden kann, weil ich nicht finden können, Fragen/Ergebnisse über Google auf es. Ich möchte das ändern stdout von einem fork() auf ein Rohr, und dann ändern Sie es zurück zu den normalen stdout.

Dies ist, was ich habe:

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);
      }
}

helloworld

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
}

Gewünschte Ausgabe:

world
PIPE OUTPUT = hello

Aktuelle Ausgabe:

hello
world
  • man perror Verwenden Sie nicht fprintf zu drucken Fehlermeldungen ohne strerror
  • Danke für den Tipp!
Schreibe einen Kommentar