Originally Posted by
Elysia
Each process runs in its own virtual memory space - it inherits nothing from the process that launched it.
fork() causes a copy of the current process to be made, including the value of all variables.
Since everything is virtual, in terms of addressing, from the application point of view, you're dealing with an exact copy that points to the same variables, which of course you're not. The value of all variables are copied.
Case in point:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
size_t i;
pid_t p = fork();
char *szMsg = "Testing!";
if(p == 0)
{
/* Child */
printf("szMsg is at address: %p\n", szMsg);
for(i=0;i<strlen(szMsg);i++)
{
printf("szMsg[%d] = [%d, %c]\n", i, szMsg[i], szMsg[i]);
}
}
else if(p > 0)
{
/* Parent */
wait(NULL);
printf("szMsg is at address: %p\n", szMsg);
for(i=0;i<strlen(szMsg);i++)
{
printf("szMsg[%d] = [%d, %c]\n", i, szMsg[i], szMsg[i]);
}
}
else
{
fprintf(stderr, "Error. Unable to fork.\n");
return 1;
}
return 0;
}
Output:
Code:
>gcc -W -Wall -ansi -pedantic -O2 fork.c
>a.out
szMsg is at address: 108d8
szMsg[0] = [84, T]
szMsg[1] = [101, e]
szMsg[2] = [115, s]
szMsg[3] = [116, t]
szMsg[4] = [105, i]
szMsg[5] = [110, n]
szMsg[6] = [103, g]
szMsg[7] = [33, !]
szMsg is at address: 108d8
szMsg[0] = [84, T]
szMsg[1] = [101, e]
szMsg[2] = [115, s]
szMsg[3] = [116, t]
szMsg[4] = [105, i]
szMsg[5] = [110, n]
szMsg[6] = [103, g]
szMsg[7] = [33, !]
>
Even though the addresses match, you're not dealing with the same exact memory space (because it's virtual).
So I would argue you are actually inheriting everything, or most of everything, from the parent process. In this context, "inheriting" means all variables retain their same values. In some cases, such as file descriptors, you actually are pointing to the same files, but this is somewhat indepth to get into atm.