Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why fprintf doesn't work in thread?

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

like image 924
roman Avatar asked Jun 30 '26 17:06

roman


1 Answers

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;
}
like image 164
Sergey Kalinichenko Avatar answered Jul 02 '26 07:07

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!