线程不刷新数据,在屏幕中显示数据时出错

Thread dont flush data, error displaying the data in the screen

本文关键字:数据 显示 出错 屏幕 刷新 线程      更新时间:2023-10-16

我正在创建一个套接字程序将数据从一台PC传输到另一台PC,但是当我发送一些二进制数据以处理到另一端时,我遇到了问题。在这种情况下,我需要一线程来侦听消息套接字,而数据套接字发送数据。所以我发现问题不在于套接字,如果我尝试将数据写入屏幕(这次没有套接字(,就会出现问题。所以我尝试使用 fflush(stdout( 刷新数据,但没有运气。代码以这种方式工作。

Initialize the 2 sockets.
Initialize 2 threads.
  One to get the data back through the data socket.
  The other send the data.    
And while sending all the data one while(true){sleep(1)} in the main function, because the data can take 1 second to be processed or one hour so i keep the program alive this way (Don't know if that is the better way).

我创建了一个较小的版本,仅使用一个线程来读取并发送到屏幕,并且主要只是一会儿。

法典:

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
const int RCVBUFSIZE=2000;
char echoString[RCVBUFSIZE];
static void * _sendExec(void *instance);
int main(){
  pthread_t m_thread;
  int merror;
  merror=pthread_create(&m_thread, NULL, _sendExec, NULL);
  while(1){sleep(1);}
}
static void * _sendExec(void *instance){
  int size;
  for(;;){
    while((size=read(fileno(stdin), echoString, RCVBUFSIZE))>0) write(fileno(stdout), echoString, size);
    fflush(stdin);
    fflush(stdout);
    pthread_exit(0);
  }
}

如果您尝试 cat 文件.tar.gz | ./a.out | tar -zvt,您可以看到并非所有数据都显示在屏幕上,如果我戴上主电源,请删除睡眠,问题是我需要数据回来,这可能需要时间。就像我做一个猫文件一样.tar.gz |ssh root@server "tar -zvt"。

谢谢大家

我知道您提供的代码不是您正在使用的实际代码。正如 wreckgar23 提到的,如果你想等待线程完成,你应该在 main 函数的末尾使用 pthread_join。你可以删除 while(1({ sleep(1(;}/pthread_exit(0(,pthread_join将使主线程等待线程完成。

同样使用 while(1(/for(;;) 也不是一个好主意......你至少可以使用一个 int 值将其设置为 0 并执行所有数据处理,直到它将其值更改为 1。您可以检查通过套接字接收的数据中的某个"消息"以获取终止命令,并将 int 的值设置为 1。(因此,您可以通过(客户端(输入来控制服务器的生命周期,整个服务器应用程序可以在处理完数据后停止。如果这样做,则还应考虑安全隐患。

还应该明确指定您正在使用的套接字类型。例如,如果您使用 udp 套接字并且您有一个小缓冲区,您可能会丢失数据。此外,您不能从缓冲区打印数据并同时写入它。(将缓冲区写入屏幕需要时间.在将数据写入屏幕时,可能会有新数据到达缓冲区并在有机会打印之前覆盖旧数据(