1

I have some C code using fork but I don't understand how it works

int hijo,i,N; int main(int argc, char*argv[]){ N=atoi(argv[1]); for(i=0;i<N;i++) if((hijo=fork())>0)break; } 

Why does this program create only one child process of the previously created process and doesn't create a process for each of the processes that exist before do the fork?

5
  • 1
    1: What's N? 2: It's unclear what you're asking; are you wondering why the children don't fork too? Commented Jun 15, 2022 at 9:21
  • 2
    This code produces no output. How do you know what it does? Commented Jun 15, 2022 at 9:27
  • Its a part of a big code, N is the number of process e.g 5, and what I try to ask is why is one process after another and no processes are created to the processes that are not just the previous one when I do the fork. It's an example from my university and they told me is that what it does but I don't understand Commented Jun 15, 2022 at 9:35
  • Form that code snippet, it is easy to add printf() traces that help understand which process execute which part of code. Commented Jun 15, 2022 at 9:36
  • 1
    When the parent calls fork(), it returns a PID of the child process. Since now there are two processes, in the parent the return of the fork is the PID of the child, but in the child the return has been a 0. Therefore, I would recommend you that always you want to use fork(), create a code structure similar to pid=fork(); if(pid==0) {/*Child code*/} else{ wait()} this last wait() is important to not leave any zombie child because childs would be running on background forever if the child program does not end. Commented Jun 15, 2022 at 9:53

1 Answer 1

1

The code is equal to this:

int hijo; int main(int argc, char*argv[]){ if (argc < 2) return 1; // let's not crash // assume i and N are global variables not shown... N=atoi(argv[1]); i = 0; if (N < 1) return 0; // do not enter loop if N < 1 do { hijo=fork(); } while (hijo <= 0 && ++i < N); } 

From this we can more easily see, that for the original parent process, where hijo value is the pid of the first child, the loop condition is false immediately, and loop ends.

Same repeats for every child process, so a process can only be parent (hijo > 0) for one forked process.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.