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?
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);
}
After the fork you have two new processes and you can know the child id in the parent but not the other way round. If you really need this you would have to open a pipe (popen) before the fork and then the parent could write this into the pipe and the child could read it.
Once the parent completes it execution and child is still running. Then child is known as orphan (as it's parent died) and it is adopted by init process if you are login by root ( whose pid =1 ).
If you want child to exit first before parent then use wait() system call and its variants.
#include <stdio.h>
#include <unistd.h>
int main()
{
int pid,pid2;
pid=fork();
if (pid<0) {
printf("fork failed");
exit(-1);
} else if (pid==0) {
printf("child id is%d",getpid());
execlp("/bin/ls","is",NULL);
printf("\nsleeping for 2 seconds using pid of child class");
sleep(2);
printf("killing the child process");
kill(getpid());
} else {
wait(NULL);
printf("The parent id is %d\n",getpid());
printf("The child id is %d\n",getpid());
printf("\nsleeping for 3 seconds without pid");
sleep(3);
printf("\nchild completed\n");
exit(0);
}
}
It is simply, because the parent process no longer exists. If you call the wait()
system function, then it will exist until the child finishes its work and you will get the parent PID.