Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Fork: pid reuse

Tags:

c

linux

fork

I wrote the following program to understand the way 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's the output I get->

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

I expected the program to go on as I'm exiting the child process instantly and fork() should reuse the pids after pid > pid_max. Why doesn't this happen?

like image 815
Zaxter Avatar asked Sep 25 '14 12:09

Zaxter


2 Answers

The exited child processes do remain in the process table as zombies. Zombie processes exist until their parent calls wait or waitpid to obtain their exit status. Also, the corresponding process id is kept, to prevent other newly created processes of duplicating it.

In your case, the process table becomes too large and the system rejects the creation of new processes.

Forking processes and then not retrieving their exit status can be regarded as a resource leak. When the parent exits, they will be adopted by the init process and then reaped, but if the parent stays alive for too long, there is no way for the system to just remove some of the zombies, because it is assumed that the parent should get interested in them at some point via wait or waitpid.

like image 166
Blagovest Buyukliev Avatar answered Nov 03 '22 15:11

Blagovest Buyukliev


Child processes also hold some resource like memory. But they are not released because parent process can not process SIGCHLD signal, which will be sent by child processes when they exit.

Those child processes will become zombie.

You can use "ps -aux" to dump those fd.

like image 34
carpenter Avatar answered Nov 03 '22 13:11

carpenter