A
Auf tntnets Seite scheinen die angegebenen Dateien nicht mehr vorzuliegen (ich krieg da jedenfalls nen 404)
jedenfalls hab ich mich grad selbst mit dem thema beschäftigt und folgenden Code fabriziert:
#ifndef __STREAMPIPE_H
#define __STREAMPIPE_H
#ifndef STREAMPIPE_BUFFERSIZE
#define STREAMPIPE_BUFFERSIZE 4096
#endif
#include <iostream>
#include <pthread.h>
using namespace std;
class StreamPipe {
friend void* DoPipe(void* StreamPipe);
protected:
pthread_t Thread;
istream* in;
ostream* out;
public:
void Start(istream& in, ostream& out);
void Start();
void Stop();
void Wait();
StreamPipe(istream& in, ostream& out);
~StreamPipe();
};
void* DoPipe(void* Pipe) {
istream* in = ((StreamPipe*)(Pipe))->in;
ostream* out = ((StreamPipe*)(Pipe))->out;
char Buffer[STREAMPIPE_BUFFERSIZE+1];
while(in->peek() != -1 && out->good()) {
in->read(Buffer, STREAMPIPE_BUFFERSIZE);
Buffer[in->gcount()] = '\0';
(*out) << Buffer;
out->flush();
}
return NULL;
}
StreamPipe::StreamPipe(istream& i, ostream& o) {
Start(i,o);
}
StreamPipe::~StreamPipe() {
Stop();
}
void StreamPipe::Start(istream& i, ostream& o) {
Stop();
in = &i;
out = &o;
Start();
}
void StreamPipe::Start() {
Stop();
pthread_create(&Thread, NULL, DoPipe, this);
}
void StreamPipe::Stop() {
pthread_cancel(Thread);
}
void StreamPipe::Wait() {
pthread_join(Thread,NULL);
}
#endif
Du erzeugst einfach ein StreamPipe Objekt und übergibst den istream und den ostream an den Konstruktor. Die Klasse erzeugt nen pthread, welcher den istream überwacht und alles, was da ankommt, an den ostream weitergibt... mit der Wait Methode kann man zB bei beendigung des Programms noch auf das ende des istreams warten und mit Stop kann man die Pipe anhalten...
damit kann man zB ein Programm schreiben, welches übergebene Dateien auf stdout ausgibt:
#include <fstream>
#include "StreamPipe.h"
using namespace std;
int main(int argc, char** argv) {
for(int i = 1; i < argc; i++) {
ifstream in(argv[i]);
StreamPipe Pipe(in,cout);
Pipe.Wait();
}
return 0;
}
wegen den pthreads muss man beim kompilieren die -lpthread option angeben...
dadurch, dass die pipe in nem eigenen thread läuft, blockiert das Programm nicht bis der istream zu ende ist - dadurch kann man zB ne datei aus nem ifstream an einen socket stream (gibt's eigentlich iostreams für sockets? ich arbeite jedenfalls an welchen...) schicken ohne zu warten, bis sie komplett übertragen ist...