gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:31:33 25 4
gpt4 key购买 nike

为什么 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

最佳答案

这是一个已知问题。 fix proposed不久前,Kaz 没有被 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

关于c - 僵尸进程即使线程仍在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26996201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com