I want use pointer to get the pid of parent process with child process of it:
int main(void){
pid_t childPid,*parentPid,pid;
childPid = fork();
if(childPid == 0 ){
printf("[Child] the parent pid is 0x%u\n", *parentPid);
}else if(childPid < 0){
printf("there is something wrong");
}else{
pid = getpid();
printf("[Parent] the pid is 0x%u\n",pid);
parentPid = &pid;
}
return (EXIT_SUCCESS);
}
the output is:
[Parent] the pid is 0x5756
[Child] the parent pid is 0x1
there must be something wrong with my code, any idea?
The child never modifies
*parentPid, so it just contains random garbage. If you want your parent PID, callgetppid.Even if you fixed the race condition, the code still wouldn’t work. Changing memory in the parent doesn’t change that memory in the child unless the memory is shared. If all memory were shared by default, the child and parent would instantly obliterate each other’s data and cause total chaos.