0
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
int main(){
    int pipefd[2];
    int status = pipe(pipefd);
    int child = fork();
    printf("%d",child);
    if(!child){
        wait(NULL);
        dup2(pipefd[0],0);
        int temp = execl("/bin/sort","sort",NULL);
        close(pipefd[0]);
    }else{
        if(!status){
            dup2(pipefd[1],1);
            close(pipefd[1]);
            int temp = execl("/bin/ls","ls",NULL);  
        }else{
            printf("Pipe error\n");
        }
    }
    return 1;
}

Here in the above code my aim is to read from child process and the parent process read from the pipefd[0] but I don't why it is not getting printed...

  • 2
    `close(pipefd[0])` needs to be before the `exec`. You also need for the child to close `pipefd[1]` and the parent to close `pipefd[0]`; each end of the pipe should be open in only one place. – Nate Eldredge Aug 27 '21 at 14:58
  • 2
    To expand on Nate's comment: `sort` will not terminate until every copy of `pipefd[1]` is closed. But since you didn't `close(pipefd[1])` in the parent before `sort` was `exec`'d, `sort` itself is keeping that pipe open. It is blocked on itself waiting for it to close a file descriptor that it will never close. – William Pursell Aug 27 '21 at 15:15
  • @WilliamPursell it worked for me but i don't understand why we need to close pipefd[1] in parent? – Juzar Antri Aug 28 '21 at 05:16
  • 1
    You need to close it in every process that has it open before the pipe is considered closed. If any process has the write side open, then a blocking read on the read side will block indefinitely waiting for data that might come. – William Pursell Aug 28 '21 at 13:32
  • regarding statements like: `int temp = execl("/bin/sort","sort",NULL);` The `exec*` family of functions only returns if the call fails. Even then, it does not return a useful value (however, it does set `errno`) Suggest: `execl("/bin/sort","sort",NULL); perror( "call to execf for sort failed" ); exit( EXIT_FAILURE );` – user3629249 Aug 29 '21 at 15:44
  • regarding: `close(pipefd[0]);` following a call to `execl()` will only get executed if the call to execl() fails. – user3629249 Aug 29 '21 at 15:45
  • regarding: `int child = fork(); printf("%d",child); if(!child)` the function: `fork()` has three kinds of returns: >0 means in the parent process. ==0 means in the child process. <0 means an error occurred. The code should be checking for and properly handling all three conditions – user3629249 Aug 29 '21 at 15:49
  • regarding: `int status = pipe(pipefd);` the (later) check for the success of the call to `pipe()` needs to be immediately after this call to `pipe()`, not several instructions later. Also, the results of the call to `pipe()` are being used, regardless of the success/failure of the call to `pipe()` in this code: `dup2(pipefd[0],0);` – user3629249 Aug 29 '21 at 15:54

0 Answers0