[질문] fork시 프로세스와 메모리 관련입니다.

seolcw의 이미지

안녕하세요 고수님들,,,
메모리를 잡아먹는 유닉스 프로그램을 만들어 메모리테스트를 해보려는 중입니다.
그래서 원하는 단위로 메모리를 짤라서 원하는 시간만큼 할당해놓고 풀어주는 프로그램을 아래와 같이 만들어 실행시켰더니 fork이후 프로세스 및 메모리 할당이 예상하는데로 작동하지가 않네요.
10초간 200메가를 100가씩 fork해 할당하려했는데 fork error가 발생하고, 하지만 원하는대로 프로세스 및 메모리는 할당되었고, 10초후 얘네는 죽고 이상하게 프로세스와 메모리 할당, 또 10초후 다른 프로세스와 메모리할당, 10초후 완료됩니다.
이유를 아시나요? 부탁드립니다.
감사합니다.

root@v5:/cwseol/scomm> cat mem.c
#include <stdio.h>
#include <malloc.h>

main(int argc, char *argv[])
{
int *p;
int i, l, m, n, c, d;

if (argc != 4)
{
printf("Usage : mem memory_size division_unit time(sec)\n");
return ;
}

l = atoi(argv[1]);
m = atoi(argv[2]);
n = atoi(argv[3]);
c = l / m;
d = l % m;
printf("This program will hold %dMB in memory for %d seconds!\n", \
l, n);
for (i=0;i<c+1;i++)
{
if (!fork())
{
if (i!=0) p = (int*)calloc(m, 1048576);
else p = (int*)calloc(d, 1048576);
sleep(n);
free(p);
}
}
}
root@v5:/cwseol/scomm> cc -o mem mem.c
root@v5:/cwseol/scomm> ps aux |grep mem |grep -v grep
root@v5:/cwseol/scomm> mem 200 100 10&
[1] 106742
root@v5:/cwseol/scomm> This program will hold 200MB in memory for 10 seconds!
ps aux |grep mem |grep -v grep
root 471236 0.0 26.0 102500 102484 pts/1 A 22:06:00 0:00 mem 200 100 10
root 458938 0.0 0.0 96 84 pts/1 A 22:06:00 0:00 mem 200 100 10
root 368742 0.0 26.0 102508 102492 pts/1 A 22:06:00 0:00 mem 200 100 10
[1] + Done mem 200 100 10&
root@v5:/cwseol/scomm> ps aux |grep mem |grep -v grep
root 520436 0.0 18.0 102500 102488 pts/1 A 22:06:10 0:00 mem 200 100 10
root 508076 0.0 13.0 174976 72548 pts/1 A 22:06:11 0:00 mem 200 100 10
root 438274 0.0 18.0 102492 102480 pts/1 A 22:06:10 0:00 mem 200 100 10
root@v5:/cwseol/scomm> ps aux |grep mem |grep -v grep
root 471246 0.0 35.0 102520 102528 pts/1 A 22:06:21 0:00 mem 200 100 10
root@v5:/cwseol/scomm> ps aux |grep mem |grep -v grep
root@v5:/cwseol/scomm>

pynoos의 이미지

소스를 BBCode를 활용하여 보기 좋게 해주세요.
간단합니다. 앞뒤로   를 넣으면 됩니다.

fork로 생성되는 child가 다시 fork를 하도록 되어 있군요.
child는 exit(0)로 종료하는 것이 논리적입니다.