I ran into a code that looks like this
int main(void){
pid_t pid;
char sharedVariable='P';
char *ptrSharedVariable=&sharedVariable;
pid = fork()
if(pid==0) {
sharedVariable = 'C';
print("Child Process\n");
printf("Address is %p\n", ptrSharedVariable);
printf("char value is %c\n", sharedVariable);
sleep(5);
} else {
sleep(5);
print("Parent Process\n");
printf("Address is %p\n", ptrSharedVariable);
printf("char value is %c\n", sharedVariable);
}
By what I learned on stack overflow, I can tell that the char value of the parent and child process will be different. The child's value is 'C' and the parent's is 'P'. I also can tell that the address in both parent and child should be the same, which is the address to 'sharedVariable'(&sharedVariable).
However here are my question.
- What is the point of assigning different char values to different processses? Because for one thing, since we can already identify each process by pid==0 or >0, wouldn't this step be a redundancy? Another reason is I don't see a point in differentiating two processes that do the same job, can't they work without letting the programmers tell them apart?
- Why let the addresses of parent and child stay the same? I can suggest that since they are assumed to proceed on similar tasks, it would be convenient to do so, because then we can just copy and paste code. I am hesitant and want to make sure.
- if I replaced fork() with vfork(), would the result of the parent's char value then be 'C'?
Thanks a million in advance.