This is kind of a technical question, maybe you can help me if you know about C and UNIX (or maybe it's really a beginners question!)
The question was raised today by analyzing some code in our course "Operating Systems". We study what it means to fork a process on UNIX, we already know that it creates a copy of the current process parallel to it, and they have separate data sections.
But then I thought that maybe if you create a variable and a pointer pointing to it before doing fork (), since the pointer stores the memory address of the variable, you can try to change the value of this variable from the child process using this pointer.
We tried code similar to this in the class:
#include <stdio.h> #include <sys/types.h> #include <stdlib.h> int main (){ int value = 0; int * pointer = &value; int status; pid_t pid; printf("Parent: Initial value is %d\n",value); pid = fork(); switch(pid){ case -1: //Error (maybe?) printf("Fork error, WTF?\n"); exit(-1); case 0: //Child process printf("\tChild: I'll try to change the value\n\tChild: The pointer value is %p\n",pointer); (*pointer) = 1; printf("\tChild: I've set the value to %d\n",(*pointer)); exit(EXIT_SUCCESS); break; } while(pid != wait(&status)); //Wait for the child process printf("Parent: the pointer value is %p\nParent: The value is %d\n",pointer,value); return 0; }
If you run it, you will get something like this:
Parent: initial value is 0
Baby: I will try to change the meaning
Child: pointer value is 0x7fff733b0c6c
Baby: I set the value to 1
Parent: pointer value is 0x7fff733b0c6c
Parent: value is 0
Obviously, the child process had no effect on the parent process. Honestly, I was expecting a "segmentation error" error due to access to an invalid memory address. But what really happened?
Remember, I'm not looking for a way to communicate with processes, this is not the main thing. I want to know what the code has done. Inside the child process, the change is visible, so it is DID.
My main hypothesis is that pointers are not absolute for memory, they relate to the process stack. But I could not find the answer (no one in the class knew and didnβt search on Google, I just found some questions about the processing of the process), so I would like to learn from you, I hope someone will find out.
Thanks for taking the time to read!