Linux fork: reusing pid

I wrote the following program to understand how fork works when called without wait () or waitpid ().

int main() { pid_t childpid; int retval = 0; int i; while(1){ //usleep(1); childpid = fork(); if (childpid >= 0) { i++; if (childpid == 0) { exit(retval); } else { //printf("childpid is %d\n", childpid); } } else { printf("total no. of processes created = %d\n", i); perror("fork"); exit(0); } } } 

Here I get the output →

 total no. of processes created = 64901 fork: Cannot allocate memory 

I expected the program to continue when I exit the child process immediately, and fork () should reuse pids after pid> pid_max. Why is this not happening?

+5
source share
2 answers

Output child processes remain in the process table as zombies. Zombie processes exist until their parent invokes wait or waitpid to get their exit status. In addition, a corresponding process identifier is stored to prevent other newly created processes from duplicating it.

In your case, the process table becomes too large, and the system refuses to create new processes.

Forking processes and then not obtaining exit status can be considered as a resource leak. When the parent exits, they will be accepted by the init process and then received, but if the parent remains too long, there is no way for the system to simply remove some of the zombies, since it is assumed that the parent should be interested in them at some point through wait or waitpid .

+7
source

Child processes also store some resources, such as memory. But they are not freed because the parent process cannot process the SIGCHLD signal that will be sent by the child processes when they exit.

These child processes will become zombies.

You can use "ps -aux" to reset these fd.

+1
source

Source: https://habr.com/ru/post/1203392/


All Articles