Processes' memory



Hi all, given this simple snippet, can you explain me how the kernel is
able to isolate the 's2' variable. I know that processes do not share
the same memory space, and I wanted to know how they deal with the
varible previously mentioned (in my example I show that the address of
the variable is the same).

Thanks, Mattia

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

int main()
{
pid_t child_pid;
const int s2_size = 5;
char *s2 = malloc(sizeof(char) * s2_size);
int i = 0;

for (i = 0; i < s2_size-1; ++i)
*(s2+i) = 'a' + i;

*(s2+s2_size-1) = '\0';

// printf("The main program process ID is %d\n", (int) getpid());

child_pid = fork();

if (child_pid != 0)
{
// printf("This is the parent process, ID %d\n", (int) getpid());
int k;
for (k = 0; k < s2_size-1; ++k)
s2[k] = 'A' + k;
// printf("The parent will sleep for a while...\n");
sleep(1);
// printf("%s\n", s2);
printf("Parent s2: %s, address: %p\n", s2, &s2);
}
else
{
// printf("This is the child process, ID %d\n", (int) getpid());
// printf("%s\n", s2);
printf("Child s2: %s, address: %p\n", s2, &s2);
}

free(s2);

return 0;
}

Output:
Child s2: abcd, address: 0xbff078a4
Parent s2: ABCD, address: 0xbff078a4
.



Relevant Pages