Search code examples
cforkpid

child and parent process id


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?


Solution

  • 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);
    }