I have a program with a parent and a child process. Before the fork(), the parent process called malloc() and filled in an array with some data. After the fork(), the child needs that data. I know that I could use a pipe, but the following code appears to work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main( int argc, char *argv[] ) {
char *array;
array = malloc( 20 );
strcpy( array, "Hello" );
switch( fork() ) {
case 0:
printf( "Child array: %s
", array );
strcpy( array, "Goodbye" );
printf( "Child array: %s
", array );
free( array );
break;
case -1:
printf( "Error with fork()
" );
break;
default:
printf( "Parent array: %s
", array );
sleep(1);
printf( "Parent array: %s
", array );
free( array );
}
return 0;
}
The output is:
Parent array: Hello
Child array: Hello
Child array: Goodbye
Parent array: Hello
I know that data allocated on the stack is available in the child, but it appears that data allocated on the heap is also available to the child. And similarly, the child cannot modify the parent's data on the stack, the child cannot modify the parent's data on the heap. So I assume the child gets its own copy of both stack and heap data.
Is this always the case in Linux? If so, where the is the documentation that supports this? I checked the fork() man page, but it didn't specifically mention dynamically allocated memory on the heap.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…