CaseyJones
CaseyJones

Reputation: 505

trying to use pipe(2) with the sort unix tool but not working

I have been struggling to find what I'm doing wrong and I can't seem to find the issue. When I compile the code below, I get an I/O error.

e.g: /usr/bin/sort: read failed: -: Input/output error

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


int main(int argc, char **argv, char **envp)
{
        int fd[2];
        pid_t pid;

        pipe(fd);

        pid = fork();
        if (pid == -1) {
                exit(EXIT_FAILURE);
        }

        if (pid == 0) { /* child */
                char *exe[]= { "/usr/bin/sort", NULL };
                close(fd[0]);
                execve("/usr/bin/sort", exe, envp);

        }
        else {
                char *a[] = { "zilda", "andrew", "bartholomeu", NULL };
                int i;

                close(fd[1]);

                for (i = 0; a[i]; i++)
                        printf("%s\n", a[i]);
        }

        return 0;
}

Upvotes: 0

Views: 645

Answers (1)

ctrl-d
ctrl-d

Reputation: 392

dup2(fd[0], 0) in the child. dup2(fd[1], 1) in the parent. close the other fd.

Upvotes: 1

Related Questions