Warum funktioniert die Umleitung von stdin in C nicht funktionieren?

Ich versuche die Umleitung von stdin von den Eltern auf das Kind durch die pipe "my_pipe", aber wenn ich mein Programm, ich sehe nicht die erwarteten Ergebnisse.

Wenn ich das Programm auszuführen, es erwartet die Eingabe von stdin, also warum hat es nicht umleiten von stdin in dup2?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>



int main(int argc, char* argv[])
{
    char* arguments[] = {"sort", NULL};

    int my_pipe[2];
    if(pipe(my_pipe) == -1)
    {
        fprintf(stderr, "Error creating pipe\n");
    }

    pid_t child_id;
    child_id = fork();
    if(child_id == -1)
    {
        fprintf(stderr, "Fork error\n");
    }
    if(child_id == 0) //child process
    {
        close(my_pipe[1]); //child doesn't write
        dup2(0, my_pipe[0]); //redirect stdin

        execvp(argv[0], arguments);

        fprintf(stderr, "Exec failed\n");
    }
    else
    {
        close(my_pipe[0]); //parent doesn't read

        char reading_buf[1];
        write(my_pipe[1], "hello", strlen("hello"));
        write(my_pipe[1], "friend", strlen("friend"));
        close(my_pipe[1]);
        wait();
    }
}
InformationsquelleAutor XavierusWolf | 2012-05-22
Schreibe einen Kommentar