user3764893
user3764893

Reputation: 707

How to handle pipes in this special case

I create a simple pipe and the result of ls -l /usr/bin command is written to it using a forked (child) process. Then in the main (parent) process I just wait for the child to finish.

    int fd[2];
    char* arg[] = {"ls", "-l" , "/usr/bin/", NULL};

    pipe(fd);

    if (fork()==0) //child
    {
        dup2(fd[1], 1);
        close(fd[0]);
        close(fd[1]);

        execvp(arg[0],arg);
    }
    else //parent
    {
        // close(fd[0]);
        close(fd[1]);       
        wait(NULL);
    }

In the child process after I execute dup2, I close both end of pipes as I will not need them anymore. In the parent I close only the write end as I need the read end.

If this code is executed it will stall. BUT, if the command was ls -l ~/Desktop/ or something similar it would terminate successfully.

Clearly ls -l /usr/bin command takes more time than ls -l ~/Desktop/, but I think it still would not matter, both of them would have to terminate.

In the parent, if I would close also the read end of the pipe, the program would terminate (which I don't want).

What is the reason of this behavior? Is there any workaround to overcome it?

Upvotes: 0

Views: 53

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754530

The problem is that a pipe has a finite capacity (which POSIX allows to be quite small, like 4 KiB; Linux may allow up to about 64 KiB, and Mac OS X allows up to 64 KiB). After the writing process has written that much data without a reading process doing the reading, it is blocked until the reading process reads some data, or the last reading process dies and there is no process left that can read the data.

Pipelines are for concurrent execution of programs. You're forcing sequential execution by trying to make the first program finish before the next starts. This is incorrect. You need to ensure that you start all the processes in the pipeline before you do any waiting for them to finish

Upvotes: 2

Related Questions