[완료]fork시 정말 메모리를 복사하는지?
제가 fork()에 대해서 보고 있는데 모든 책에 fork는 메모리를 복사해 부모 프로세스와 자식 프로세스로 나뉜다고 하는데.
제가 환경변수에 관하여 테스트해본 결과 복사해서 새로운 메모리 영역에 자식프로세스를 할당하는 것이 아니라, 같은 곳을 쉐어 하는 것 같은데 제 프로그램이 잘못된 것인가 궁금합니다.
---
#include
#include
#include
#include
// define a unit of capacity.
#define ONEGB 1073741824
#define ONEMB 1048576
#define ONEKB 1024
//////////////////////
//
// name: addr
// import: unsigned long a
// export: char *
// assertion: the function does some calculations for converting an address to a size of address.
// Therefore, it is easy to understand the location of the address.
//
/////////////////////
char *addr(unsigned long a)
{
unsigned long r; // remainder
// calculate a giga-byte. e.g) 10^9
r = (unsigned long) a;
int gb = (int) ( r / ONEGB );
// calculate a mega-byte. e.g) 10^6
r -= gb * ONEGB;
int mb = (int) ( r / ONEMB );
// calculate a kilo-bye. e.g) 10^3
r -= mb * ONEMB;
int kb = (int) ( r / ONEKB );
// calculate a byte
r -= kb * ONEKB;
int b = (int) (r);
// the dynamic memory is allocated in char's pointer 'p' and the size of the dynamic memory is 64.
char *p = malloc(64);
// making a output of this function.
sprintf(p, "\t\t%4dGB, %4dMB, %4dKB, %4d", gb, mb, kb, b);
return p;
}
int main()
{
int child, ret, i;
char *getenv(), *p;
printf("STEP1: To set the environment variable(named myname, assigned \"min chul hong \" \n");
if( (ret = setenv("myname","---- --- --",0)) < 0){
printf("can not set the environment variable");
exit(1);
}
sleep(1);
printf("STEP2: to create a child process using fork()\n");
sleep(1);
printf("STEP3: the child will be taken out the environment variable called myname\n");
sleep(1);
if( (child = fork()) < 0 ){
printf("can not fork\n");
exit(2);
}else if( child == 0){
// child process
extern char **environ; // declare environ pointer to get all environment varibles.
if( (p = getenv("myname")) == (char *) 0)
printf("[child] not found \n");
else
printf("[child] myname=%s\n",p);
// to get the address of all environment variables.
printf("The address of start and end of its environment in child process\n");
for( i=0 ; environ[i] != (char *) 0 ; i++)
printf("The address of command line argument[%d] at %s\n", i, addr( (unsigned long) environ[i]) );
exit(0);
}else{
// parent process
extern char **environ; // declare environ pointer to get all environment varibles.
wait(child);
// to get the address of all environment variables.
printf("The address of start and end of its environment in parent process\n");
for( i=0 ; environ[i] != (char *) 0 ; i++)
printf("The address of command line argument[%d] at %s\n", i, addr( (unsigned long) environ[i]) );
exit(0);
}
return 0;
}
복사 오버헤드가
복사 오버헤드가 크기 때문에
Copy On Write(COW)라는 방법을 사용합니다.
설명하자면 길고 -_-;
구글에서 찾아보시면 바로 나옵니다.
댓글 달기