User_X220
User_X220

Reputation: 53

getpid() returns unexpected value

I am trying to run this piece of hello world code :

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> 
#include <sys/types.h>

char string1[] = "\n Hello";
char string2[] = " World.\n";

int main(void)
{

int childpid;

if((childpid = fork() ) == -1){
    printf("\n Can't fork.\n"); 
    exit(0);
}

else if(childpid == 0){ /* Child process */
    printf("\n Child: My pid = %d, Parent pid = %d \n", getpid(), getppid());
    exit(0);    
}

else{ /* Parent Process */
    printf("\n Parent: Child pid = %d, My pid = %d, Parent pid = %d \n", childpid, getpid(),getppid());
    exit(0);
}

} 

The output I am getting is different each time with regard to the child's parent PID :

 ~$ ./f

 Parent: Child pid = 6394, My pid = 6393, Parent pid = 27383 

 Child: My pid = 6394, Parent pid = 1842 

 ~$ ./f

 Parent: Child pid = 6398, My pid = 6397, Parent pid = 27383 

 Child: My pid = 6398, Parent pid = 6397 

When I checked to which process the pid = 1842 belongs to I found that it is the pid of /sbin/upstart --user. Anybody has an interpretation of these results please.

Upvotes: 0

Views: 581

Answers (1)

Oo.oO
Oo.oO

Reputation: 13375

You have race condition. Sometimes, your parent finishes a little bit faster, these are the cases when you see this strange result (different parent ID).

Sleep for a while inside parent and see what happens.

In fact, you can wait for your child: waitpid

...
int status;
waitpid(childpid, &status, 0);
printf("\n Parent: Child pid = %d, My pid = %d, Parent pid = %d \n", childpid, getpid(),getppid());
exit(0);
...

Upvotes: 4

Related Questions