c - From where does fork() execute inside a loop? -
consider below code, programme start executing after fork() within loop ? i'm not able understand output.
#include <stdio.h> #include <sys/types.h> int parent_code() { printf("[%d] parent\n",getpid()); } int child_code() { printf("[%d] child\n",getpid()); } int main() { int i; pid_t pid; for(i=0;i<4;i++) { pid = fork(); if(pid == 0) { child_code(); } else { parent_code(); waitpid(pid,&i,0); } } }
output :
[4896] parent [4897] kid [4897] parent [4898] kid [4898] parent [4899] kid [4899] parent [4900] kid [4898] parent [4901] kid [4897] parent [4902] kid [4902] parent [4903] kid [4897] parent [4904] kid [4896] parent [4905] kid [4905] parent [4906] kid [4906] parent [4907] kid [4905] parent [4908] kid [4896] parent [4909] kid [4909] parent [4910] kid [4896] parent [4911] kid
update where kid programme starts execution ?
won't there fork bomb (child 1 time again invoking fork) if starts top ? in programme i'm expecting kid process start execution line if(pid == 0) {
, want 1 parent process , 4 kid process. have gone wrong in doing ?
one easy way understand fork
scheme phone call view function returns twice. returns 1 time in parent, normal function , 1 time again in new process. both processes go on fork
"returned".
i want 1 parent process , 4 kid process. have gone wrong in doing that
think of first kid process. calls child_code()
, it forks. children fork if can go through loop. easy way prevent phone call break
after child_code
.
c linux fork
No comments:
Post a Comment