c - child and parent process id -
just got confused parent pid value in child process block. program given below:
int main(int argc, char *argv[]) { pid_t pid; pid=fork(); if(pid==-1){ perror("fork failure"); exit(exit_failure); } else if(pid==0){ printf("pid in child=%d , parent=%d\n",getpid(),getppid()); } else{ printf("pid in parent=%d , childid=%d\n",getpid(),pid); } exit(exit_success); }
output: pid in parent=2642 , childid=2643
pid in child=2643 , parent=1
in "advanced unix programming" says child process can parent process id using getppid() function. here getting "1" "init" process id.
how can parent pid value in child process block.. please me in getting output.
i executed in "linux mint os" in "windriver" os not getting problem. program change behaviour according os?
that's because father can / exit before son. if father exists without having requested return value of it's child, child owned process pid=1. on classic unix or gnu systems systemv init.
the solution use waitpid()
in father:
int main(int argc, char *argv[]) { pid_t pid; pid=fork(); if(pid==-1){ perror("fork failure"); exit(exit_failure); } else if(pid==0){ printf("pid in child=%d , parent=%d\n",getpid(),getppid()); } else{ printf("pid in parent=%d , childid=%d\n",getpid(),pid); } int status = -1; waitpid(pid, &status, wexited); printf("the child exited return code %d\n", status); exit(exit_success); }
Comments
Post a Comment