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

lik*_*ern 7 c linux multithreading posix pthreads

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

在下面的代码中我:

  1. 使用一个主线程创建进程
  2. 创建一个新的分离线程
  3. pthread_exit 主线程
  4. pthread_exit 分离的线程

在#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
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 5

这是一个已知的问题。一个修复提出了前一阵子由卡兹没有被乌利齐·德雷珀接受。他对此的评论是:

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.
Run Code Online (Sandbox Code Playgroud)

在此处阅读邮件链以获取更多讨论:

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