僵尸进程即使线程仍在运行

时间:2014-11-18 14:03:31

标签: c linux multithreading pthreads posix

为什么Linux认为主线程终止为僵尸进程的进程有什么办法可以避免这种情况?

在下面的代码中我:

  1. 使用一个主线程创建一个进程
  2. 创建新的分离主题
  3. pthread_exit主线程
  4. pthread_exit分离的主题
  5. 在#3之前,ps(1)将我的流程显示为正常流程。但是,在#3之后,ps(1)将我的流程显示为僵尸(例如,2491 pts/0 00:00:00 thread-app <defunct>,即使它仍然有正在运行的线程。

    是否可以退出主线程但避免进入僵尸状态?

    代码:

    #include <stdio.h>
    #include <pthread.h>
    #include <unistd.h>
    #include <stdlib.h>
    
    void *thread_function(void *args)
    {
    printf("The is new thread! Sleep 20 seconds...\n");
    sleep(20);
    printf("Exit from thread\n");
    pthread_exit(0);
    }
    
    int main(int argc, char **argv)
    {
    pthread_t thrd;
    pthread_attr_t attr;
    int res = 0;
    res = pthread_attr_init(&attr);
    res = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    res = pthread_create(&thrd, &attr, thread_function, NULL);
    res = pthread_attr_destroy(&attr);
    printf("Main thread. Sleep 5 seconds\n");
    sleep(5);
    printf("Exit from main process\n");
    pthread_exit(0);
    }
    
    # ./thread-app
    

2 个答案:

答案 0 :(得分:4)

这是一个已知问题。一段时间之前由Kaz发现的fix proposed并未被Ulrich Drepper接受。他对此的评论是:

I haven't looked at the patch nor tried it.

If the patch changes the behavior that the main thread, after calling
sys_exit, still react to signals sent to this thread or to the process
as a whole, then the patch is wrong. The userlevel context of the
thread is not usable anymore. It will have run all kinds of
destructors. The current behavior is AFAIK that the main thread won't
react to any signal anymore. That is absolutely required.

阅读邮件链,以便在此处进行更多讨论:

http://lkml.iu.edu/hypermail/linux/kernel/0902.0/00153.html

答案 1 :(得分:3)

操作系统认为您的进程是僵尸,因为操作系统启动的主线程返回(即退出)。如果您不想要这种行为,那么请不要让主线程退出。