2016年3月30日 星期三

Zombie process in three ways.

Zombie process world.

前言


反正就是! 只要爸爸掛掉了,小孩要哭也找不到人可以哭,那就會一直卡在那邊! 完全不能結束!!



(但是我也有查到有人說parent process沒有設定waitpid的system call,所以child結束時,parent process雖然還在跑,但是child process卻會hang在那邊沒有人接收。)

其實總歸一句,就是zombie得出現,都是因為沒有人關心他們。 所以做出zombie process。

根據Zombie process wiki,可以發現Zombie Process跟Orphan Process不同的。

防止Zombie 出來害世


You have three methods to avoid creating zombies:
  1. Add waitpid() somewhere in the parent process. For example, doing this will help:
    pid=fork();
    if (pid==0) {
        exit(0);    
    } else {
        waitpid(pid);  // <--- ...="" call="" code="" parent="" reaps="" some="" this="" zombie="">
  2. Perform double fork() to obtain grandchild and exit in child while grandchild is still alive. Grandchildren will be automatically adopted by init if their parent (our child) dies, which means if grandchild dies, it will be automatically waited on by init. In other words, you need to do something like this:
    pid=fork();
    if (pid==0) {
        // child
        if (fork()==0) {
            // grandchild
            sleep(1); // sleep a bit to let child die first
            exit(0);  // grandchild exits, no zombie (adopted by init)
        }
        exit(0);      // child dies first
    } else {
         waitpid(pid);  // still need to wait on child to avoid it zombified
         // some parent code ...
    }
    
  3. Explicitly ignore SIGCHLD signal in parent. When child dies, parent gets sent SIGCHLD signal which lets it react on children death. You can call waitpid() upon receiving this signal, or you can install explicit ignore signal handler (using signal() or sigaction()), which will make sure that child does not become zombie. In other words, something like this:
    signal(SIGCHLD, SIG_IGN); // <-- ...="" be="" become="" child="" code="" created="" don="" else="" exit="" fate="" here="" if="" ignore="" it="" let="" not="" parent="" pid="=0)" should="" some="" t="" zombie="">

沒有留言:

張貼留言