Understanding fork () in for loop

I have a problem with understanding fork(). Can someone explain to me what this program will print? Because I'm preparing for the exam, and this is a typical question. It is in this case:

#include <stdio.h>

int main(int argc, char **argv) {
    int i;
    for(i = fork(); i < fork(); i++)
        execlp("echo", "sono", argv[0], 0);
    system("echo i+$i");
}

For me, what is not clear is the line

for(i = fork(); i < fork(); i++)

What does it mean? Thanks to everyone in advance.

+3
source share
2 answers

Transferring the first full iteration from initialization to all processes ending the first context of the loop, the following will happen:

1. Initializer

i initialized from i = fork();

  • Parent process :i = pid(child1)
  • Child process child1 :i = 0

Clicking a conditional test in each process is something interesting.

2. Process: parent

i < fork() , child2. pid(child2) , pid(child1), ,

3. : child1

  • i

  • i < fork() , child3. pid(child3) , i ( , ), , child1

4. : child2

  • i , i pid(child1)
  • i < fork(), fork() eval 0. ...
  • i < fork() child1(pid) < 0, . , for .

5. : child3

  • i = 0 , child1.
  • i < fork(), fork() eval 0. ...
  • i < fork() 0 < 0, . for.

parent child1 , . (child2 child3) . :

6.

  • execlp("echo", "sono", argv[0], 0);
  • child1 execlp("echo", "sono", argv[0], 0);
  • child2 system("echo i+$i"); .
  • child3 system("echo i+$i"); .

: for-conditional . , , execlp(). , , system(). , - ( , ), fork() .

, fork().. , , , fork() , .


: , pid-rollover, reset " ", child2 pid, , child1 pid. ( ), :

  • system("echo i+$i"); .
  • child1 execlp("echo", "sono", argv[0], 0);
  • child2 system("echo i+$i"); .
  • child3 system("echo i+$i"); .

, , , .

+5

. , , ""

int main(int argc, char **argv) {
    int i;
    for(i = fork(); i < fork(); i++)
        execlp("echo", "sono", argv[0], 0);
    system("echo i+$i");
}

:

i = fork();

i PID

execlp("echo", "sono", argv[0], 0);

@Whozcraig ( 1- )

"sono a.out" ( a.out). execlp() .

, fork()

:

i = fork();

i 0, , .

execlp("echo", "sono", argv[0], 0);

... , .

* , , fork() ing .

, , , , . , execlp().

N.B.: system("echo i+$i"); - , $i . .

, .

+3

All Articles