0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Which "other" fd? and also, where does dup2 get called? before or after the close(fd[x]) in both child/parent?
close fd[1] in the child and fd[0] in the parent. This is not strictly necessary, but better, since you don't leave open unused descriptors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.