child and parent process id
That's because the father can / will exit before the son. If a father exists without having requested the return value of it's child, the child will get owned by the process with pid=1. What is on classic UNIX or GNU systems SystemV init.
The solution is to 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 and parent=%d\n",getpid(),getppid());
}
else{
printf("pid in parent=%d and childid=%d\n",getpid(),pid);
}
int status = -1;
waitpid(pid, &status, WEXITED);
printf("The child exited with return code %d\n", status);
exit(EXIT_SUCCESS);
}
Comments
-
Santosh Sahu almost 2 years
Just got confused with parent pid value in child process block. My program is 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 and parent=%d\n",getpid(),getppid()); } else{ printf("pid in parent=%d and childid=%d\n",getpid(),pid); } exit(EXIT_SUCCESS); }
Output: pid in parent=2642 and childid=2643
pid in child=2643 and parent=1
In "Advanced Unix programming" it says that child process can get parent process id using getppid() function. But here I am getting "1" which is "init" process id.
How can I get the parent pid value in the child process block.. Please help me in getting output.
I executed in "Linux Mint OS" but in "WindRiver" OS I am not getting this problem. Does this program change behaviour according to OS?
-
melpomene about 7 yearsPossible duplicate of Why getppid() from the child return 1
-
-
Santosh Sahu over 10 yearsI put "sleep(2)" at the end of program and is working fine and your answer is correct.
-
Anantha Raju C over 6 yearsprovide an explanation to your answer
-
Rishabh Kumar over 6 yearsThis is basic c program for calculate the child id and parent id , including the sleep function.