Question

I'm using pipe to send an array of numbers to another process to sort them. So far, I'm able to get the result from another process using fdopen. However, I can't figure out how to send data from the pipe as stdin for another process.

Here is my code:

        int main ()
        {
            int fd[2], i, val;
            pid_t child;
            char file[10];
            FILE *f;

        pipe(fd);

        child = fork();
        if (child == 0)
        {
            close(fd[1]);
            dup2(fd[0], STDIN_FILENO);
            close(fd[0]);
            execl("sort", "sort", NULL);

        }
        else
        {
            close(fd[0]);
            printf ("BEFORE\n");
            for (i = 100; i < 110; i++)
            {
                write(fd[1], &i, sizeof (int));
                printf ("%d\n", i);
            }
            close(fd[1]);
            wait(NULL);
        }
    }

By the way, how can the other process get input? scanf?

Was it helpful?

Solution

I think your pipe is set up correctly. The problems may start at execl(). For this call you should specify an absolute path, which is probably /bin/sort if you mean the Unix utility. There is also a version of the call execlp() which searches automatically on the PATH.

The next problem is that sort is text based, more specifically line based, and you're sending binary garbage to its STDIN.

In the parent process you should write formatted text into the pipe.

FILE *wpipe = fdopen(fd[1], "w");
for (i = 100; i < 110; i++) {
    fprintf(wpipe, "%d\n", i);
    ...
}
fclose(wpipe);

A reverse loop from 110 down to 100 may test your sorting a bit better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top