title: Zombie process even though threads are still running
body: <p>Why does Linux consider a process whose main thread has terminated to be a zombie process, and is there any way to avoid this?</p>
  
  <p>In the code below I:</p>
  
  <ol>
  <li>Create a process with one main thread</li>
  <li>Create a new detached thread</li>
  <li><code>pthread_exit</code> the main thread</li>
  <li><code>pthread_exit</code> the detached thread</li>
  </ol>
  
  <p>Before #3, <code>ps(1)</code> shows my process as a normal process.  After #3, however, <code>ps(1)</code> shows my process as a zombie (e.g., <code>2491 pts/0    00:00:00 thread-app &lt;defunct&gt;</code>) <em>even though it still has running threads.</em></p>
  
  <p>Is it possible to quit the main thread but avoid going into a zombie state?</p>
  
  <p>Code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  
  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(&amp;attr);
  res = pthread_attr_setdetachstate(&amp;attr, PTHREAD_CREATE_DETACHED);
  res = pthread_create(&amp;thrd, &amp;attr, thread_function, NULL);
  res = pthread_attr_destroy(&amp;attr);
  printf("Main thread. Sleep 5 seconds\n");
  sleep(5);
  printf("Exit from main process\n");
  pthread_exit(0);
  }
  
  # ./thread-app
  </code></pre>