Why fprintf doesn't work in thread?

c, io, multithreading, pthreads, stdout

Solution

You are missing a call of `pthread_join`: if the main program exits before `printf`'s output gets to the console, you see nothing printed.

Adding `pthread_join(tid, NULL);` to your example fixes the output:

#include <pthread.h>
#include <stdio.h>

void *listen_t(void *arg){
  fprintf(stdout, "test\n");
  fflush(stdout);
}

int main(int argc, char **argv){
  pthread_t tid;
  int err;

  err = pthread_create(&tid, NULL, &listen_t, NULL);
  if (err != 0){
    printf("\ncan't create thread :[%d]", strerror(err));
  }
  else{
    printf("\n Thread created successfully\n");
  }
  pthread_join(tid, NULL);
  return 0;
}

Problem

I'm creating a thread with `pthread_create`. Inside the thread function i use ``` fprintf(stdout, "text\n"); ``` But this doesn't output anything to the console. The same problem is with `printf`. I've also tried to flush stdout buffer without any success. So the question is how to print anything to the console from a thread? UPD: ``` void *listen_t(void *arg){ fprintf(stdout, "test\n"); fflush(stdout); } int main(int argc, char **argv){ pthread_t tid; int err; err = pthread_create(&tid, NULL, &listen_t, &thread_params); if (err != 0){ printf("\ncan't create thread :[%s]", strerror(err)); } else{ printf("\n Thread created successfully\n"); } return 0; } ``` The code from main works fine. But the thread doesn't output anything

Original source