Warm tip: This article is reproduced from stackoverflow.com, please click
c for-loop loops

Undestanding for loop in pipe creation in C

发布于 2020-03-28 23:15:17

I have a comprension question about this code that I am currently studying: this function is used in a C Shell implementation to execute piped commands. I can't understand how the person who wrote it got to know how many pipes to close (why is the limit 2*com- 2)?

        for(i = 0; i < 2*com - 2; i++) close(pip[i]);
        for(i = 0; i < com; ++i) {
                waitpid(pid, &status, WUNTRACED);

prog-fh 2020-01-31 18:10

In this program, num_pipe is not actually the number of pipes but the number of commands (very bad name indeed!).
Between two commands you need one pipe, between three commands you need two pipes ... between N commands you need N-1 pipes.
Each pipe relies on two file descriptors (one for reading, one for writing) thus 2*(num_pipe-1) file descriptors are needed for num_pipe commands.
note: the malloc() does not allocate an array of integer pointers (as stated in the question) but an array of integers.

Following this logic, I would have written for(i = 0; i < 2*(num_pipe-1); i += 2) but 2*(num_pipe-1) equals to 2*num_pipe-2 and since the step is 2, the loop condition is the same with the limit 2*num_pipe-3.
It's just terribly confusing in my opinion.