Why does Linux consider a process whose main thread has terminated to be a zombie process, and is there any way to avoid this?
In the code below I:
- Create a process with one main thread
- Create a new detached thread
pthread_exit
the main threadpthread_exit
the detached thread
Before #3, ps(1)
shows my process as a normal process. After #3, however, ps(1)
shows my process as a zombie (e.g., 2491 pts/0 00:00:00 thread-app <defunct>
) even though it still has running threads.
Is it possible to quit the main thread but avoid going into a zombie state?
Code:
#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