Skip to content
Advertisement

fork: child process doesn’t stay in an infinite loop

#include <stdio.h>
#include <unistd.h>

int main()
{
    pid_t pid;  

    pid = fork();
    printf("pid : %dn", getpid());

    if( pid == 0)
    {
        printf("child: pid : %d n", getpid());
        while(1);
    }
    else
    {
        printf("parent: pid : %d n", getpid());
        //while(1);
    }
}

In the above code snippet inside if statement if we put while(1), it doesn’t remains blocked and when enter key is pressed program is exited, but in case of parent if we put while(1), parent remains blocked until we give ctrl+c. Please clarify this behaviour of child.

Advertisement

Answer

In the above code snippet inside if statement if we put while(1), it doesn’t remains blocked

The child process doesn’t exit actually; it just becomes an orphan process because its parent exits. The orphaned chuld process will be adopted by the init process of your system. You can see it via ps command.

But if you put the while(1); in the parent process it remains blocked.

Basically whichever process has while(1); infinite loop, it’s still running. When parent exits you get the prompt back and the child becomes orphan. But the child process is still running.

In general, you need to wait(2) for the child process in the parent process to reap child processes.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement