Today, I wrote a test code for fork/execvp/waitpid. In the parent process, it fork 100 child processes which only execute "date" to print the current datetime. When any child process die, the parent process will receive a SIGCHLD signal. Then, the parent process will re-fork-execvp the child process again.
I find the system memory(NOT includes the buffers and caches) will go higher and higher and even I shutdown all of the parent process and the child processes, it will not go down. Why?
My environment is Linux 2.6.9 and g++ 3.4.2
The following is my code:
//////////////////////////////////////////////////////////////////////////////////
// fork.cpp
// g++ -Wall fork.cpp -o fork
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
char* argv[] = { "data", (char*)0 };
void run()
{
// Child process
if (fork() == 0)
if (execvp("date", argv) < 0)
exit(0);
}
// SIGCHLD signal handler
void sig_child(int sig)
{
pid_t pid;
int stat;
while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
run();
}
int main()
{
// Setup signal handler
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = sig_child;
sigemptyset(&act.sa_mask);
if (sigaction(SIGCHLD, &act, 0) < 0)
return -1;
// Run 100 child processes
for (int n = 0; n < 100; n++)
run();
// Zzz...
for (;

pause();
return 0;
}
//////////////////////////////////////////////////////////////////////////////////
Thanks,
Richard