繁体   English   中英

为什么fprintf在线程中不起作用?

[英]Why fprintf doesn't work in thread?

我正在用pthread_create创建一个线程。

我使用的线程函数内部

fprintf(stdout, "text\n");

但这不会向控制台输出任何内容。 printf同样的问题。 我也尝试刷新stdout缓冲区而没有任何成功。 所以问题是如何从一个线程打印任何东西到控制台?

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;
}

主要代码很好。 但是线程没有输出任何东西

您缺少对pthread_join的调用:如果主程序在printf的输出到达控制台之前退出,则您看不到任何打印。

添加pthread_join(tid, NULL); 您的示例修复输出:

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM