线程不刷新数据,在屏幕中显示数据时出错
Thread dont flush data, error displaying the data in the screen
我正在创建一个套接字程序将数据从一台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 套接字并且您有一个小缓冲区,您可能会丢失数据。此外,您不能从缓冲区打印数据并同时写入它。(将缓冲区写入屏幕需要时间.在将数据写入屏幕时,可能会有新数据到达缓冲区并在有机会打印之前覆盖旧数据(
- 从数据库实时显示QT c++中的数据
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- QChart在使用QDateTimeAxis时不显示任何系列数据
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- 访问和打印元组中的数据,并使用 C++14 使用模板函数显示数据
- 运算符重载以显示用户定义的数据类型
- 如何在不使用委托的 QML 中显示模型数据
- 从文本文件中读取并输入到数组结构中,然后显示读取的数据C++
- 如何从amd gpus的显示输出中获取图像数据
- 它不显示数据,只显示永无止境的循环
- C++ 矢量不显示包含对象的数据
- 如何在数据文件中查找和显示内容
- Qt - 将空指针(原始数据)转换为 QImage 并将其显示在标签上
- 在QT C++编辑Qtable模型数据时,我需要得到一个小盒子,我需要显示编辑文本,这怎么可能?
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 如果构造函数和析构函数可以获取和显示(打印)数据,为什么我们需要 getter 和 setter?
- 在网格视图中显示数据 - 基于 MFC c++ 对话框的应用程序
- 使 XML 数据显示在 Blackberry 10 Cascades QML 中的 listItemComponents
- 提示用户键入 0 到 99 之间的 20 个整数.从该数据显示质数