Fork () for for () loop

I am trying to do my homework where I need to use fork() , but I do not know why I cannot stop my forks after starting them through the for loop:

 #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> int main(int argc, char *argv[]){ int limit = argc/2; if(argc%2 == 0){ perror("the number of arguments given must pe even!"); exit(1); } int i; for(i=0; i<=limit; i++){ if(fork()==-1){ perror("childes couldn't be created\n"); exit(1); } if(fork()==0){ printf("fork: %d \n",i); exit(1); } wait(0); } printf("exiting...\n"); return 0; } 

Conclusion:

 warzaru@ubuntu :~/OS/UprocH$ ./exe abcd fork: 0 fork: 0 fork: 1 fork: 1 fork: 1 fork: 2 fork: 2 fork: 1 fork: 2 exiting... exiting... fork: 2 exiting... exiting... fork: 2 exiting... exiting... exiting... warzaru@ubuntu :~/OS/UprocH$ fork: 2 fork: 2 fork: 2 exiting... 
+6
source share
2 answers

Danielle Fisher made me answer.

Edit:

 if(fork()==-1){} // first fork if(fork()==0){} // second fork 

To:

 pid = fork(); if(pid == -1) { ... //failed } else if(pid == 0) { ... //success } 

Or use the switch statement:

 switch(fork()) { case -1: ... // failed break; case 0: ... // success break; } 
+15
source

You can use execl () or some other variant of exec, this ensures that the created child does not inherit anything from the parent. This will allow you to create children with a for loop without going into the exponential explosion of a child. Change the arguments to the execl function accordingly and you can create 3 processes, for example:

 main() { int i,pid[3]; for(i=0;i<3;i++) { pid[i]=fork(); if (pid[i]==0) execl("path",0,0); } sleep(2); } 
0
source

Source: https://habr.com/ru/post/914845/


All Articles