title: pthread_exit(NULL) segfaults
body: <p>I have a project using pthreads; there's the main thread and a sub-thread and a pipe between them. It's all working fine, except <em>sometimes</em> it doesn't work. The sub thread runs a command interpreter and an ncurses-based GUI shuttles (some) input over the pipe to it. </p>
  
  <p>I create the thread normally (thread is a pthread_t file-scope variable, interp_start is the function)</p>
  
  <pre><code>if (pthread_create(&amp;thread, NULL, interp_start, NULL)) { perror("couldn't create thread"); return; }
  </code></pre>
  
  <p>Then, if the interpreter thread receives an "exit" command from the user, it calls interp_exit</p>
  
  <pre><code>fclose(output);
  pthread_exit(NULL);
  </code></pre>
  
  <p>The main thread has a select() that examines, among other things, output's FD and calls a function that read()s from the FD:</p>
  
  <pre><code>int num=read(interp_output[0], &amp;ch, 1);
  if (num==0) shell_done();
  if (num==-1) perror("read");
  </code></pre>
  
  <p>The intended behavior, which often works, is to close the FILE* in the thread, which makes the select() report ready, which makes the read() happen, which returns 0, which calls shell_done(). This does, after some simple and unrelated cleanup:</p>
  
  <pre><code>//fprintf(stderr, "joining thread\n");
  pthread_join(thread, NULL);
  //fprintf(stderr, "joined\n");
  exit(EXIT_SUCCESS);
  </code></pre>
  
  <p>All of this <em>sometimes</em> segfaults. Usually it's fine. If I uncomment those two printfs, if it fails I get neither (it segfaults in pthread_exit) or just the first (it segfaults in pthread_join).</p>
  
  <p>I'm not messing with 'thread' at any other point, and I'm only dealing with null pointers. What's the deal? I'd be looking elsewhere except I'm consistently having problems at one of those two lines - once even at restore_sem_to_pool. I think it has to be the way I'm killing the thread, but I'm doing just about the simplest thing possible.</p>
  
  <p>Thanks in advance...</p>