I’m creating a socket program to transfer data from one pc to another, but i have a problem when i send some binary data to process to the other side.
In this case i need one thread to listen the message socket while the data socket send the data.
So i discovered that the problem wasn’t the socket, the problem happens if i try to just write the data to the screen (no socket this time).
So i tried to flush the data using fflush(stdout) and no luck.
The codes work in this way.
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 pthread_join(m_thread2) 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.
I created a smaller version using two thread to read and send to the screen and in the main just the while.
Code:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
const int RCVBUFSIZE=2000;
char echoString[RCVBUFSIZE];
int recvMsgSize;
static void * _sendExec(void *instance);
static void * _recvExec(void *instance);
int main(){
pthread_t m_thread, m_thread2;
int merror, merror2;
merror=pthread_create(&m_thread, NULL, _sendExec, NULL);
merror2=pthread_create(&m_thread2, NULL, _recvExec, NULL);
pthread_join(m_thread2, NULL);
}
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);
}
}
static void * _recvExec(void *instance){
while(1){
//recvMsgSize=msgTmp->recv(buffer, RCVBUFSIZE)
write(fileno(stdout), "", 0);
sleep(1);
}
}
if you try cat file.tar.gz | ./a.out | tar -zvt you can see that not all the data is showed on the screen, if i put on the main, remove the pthread_join its ok, the problem is i need the data back and it can take time.
It’s just like if i do an cat file.tar.gz | ssh root@server "tar -zvt".
The problem is, i just can kill the sendExec after receive all the data back using the recvExec, but it just flush the stdin to me after
Changed the code and removed the socket part, just to illustrate the problem
Thanks people
In your example,
taris waiting for more input because you never provide an end-of-file indication. Try this:While adding
fclosefixes your sample program, I wouldn’t necessarily recommend it in your main program. Your sample still has an infinite loop in it (in_recvExec) and will never terminate.