开发者

Fork and Zombie process

开发者 https://www.devze.com 2023-03-27 22:03 出处:网络
I am trying some simple code on fork.When I give code like this, it works fine. It will print I am the child

I am trying some simple code on fork. When I give code like this, it works fine. It will print

I am the child

I am the parent

and then waits for 30 seconds. I understand this is due to switching between these two process. First child executes then parent and then child...

#include<stdio.h>
#include<stdlib.h>
main()
{
    int pid;
    pid=fork();
    if(pid==0)
    {
        printf("\nI am the child\n");
        sleep(30);
        exit(0);
    }
    if(pid>0)
    {
        printf("\nI am the parent\n");
        wait();
    }
}

But when I gave like (without wait in parent)

#include<stdio.h>
#include<stdlib.h>
main()
{
    int pid;
    pid=fork();
    if(pid==0)
    {
        printf("\nI am the child\n");
        sleep(30);
        exit(0);
    }
    if(pid>0)
    {
        printf("\nI am the parent\n");

    }
}

it just prints

I am the child

I am the parent

and exits ( no waiting for 30 seconds).

So is it because without wait call parent exits and child still executing? But why is it not showing up in terminal (the waiting)?

Whether parent becomes z开发者_开发技巧ombie here?


Your observations are correct.

The terminal waits for the original processes (which is the parent) to exit. It doesn't wait for any child processes to exit.

Zombies: A process is a zombie if it has exited but its parent has not called wait() on it.

In your case, the parent does not become a zombie because the terminal is waiting for it.


  1. Yes.
  2. The grandparent never waits on children; children without a parent are reparented to init.
  3. No, it dies.


The shell is waiting for the parent to finish but not the child.

The child becomes a zombie after 30 seconds (that the shell will clean up with the next prompt).


On the second example the child becomes orphan because the parent had returned while the child is alive. Orphan process belong to init and not the shell, that's why it's not showing up. There is no zombies in your two code samples. Zombies are when a parent is alive an child is dead and the parent doesnt call wait the child becomes zombie.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号