From: Simon Strandgaard <0bz63fz3m1qt3001@...> Date: 2003-05-09T09:55:32+09:00 Subject: Re: capture output Problem is almost solved, thanks for pointing me in the right direction. I have been experimenting a little with a pipe between 2 threads :-) TODO: this has to be integrated into my embedding code. This might have others interest. > cat Makefile all: g++ main.cpp -lc_r > > cat main.cpp /* tutorial on pthread http://www.llnl.gov/computing/tutorials/workshops/workshop/pthreads/MAIN.html tutorial on select/pipe http://thor.prohosting.com/~nupshot21/Unix/sockets/node44.shtml http://thor.prohosting.com/~nupshot21/Unix/sockets/node46.shtml */ #include // pthread_xxx #include // pipe, select #include // FIONREAD #include using namespace std; struct ThreadArgument { int fd; }; void my_thread(ThreadArgument *arg) { cout << "thread is running. Will read data from pipe." << endl; int fd = arg->fd; fd_set readset; FD_ZERO(&readset); FD_SET(fd, &readset); while(1) { fd_set set = readset; timeval tv; tv.tv_sec = 2; tv.tv_usec = 0; // wake up when someone sends us data or on timeout int result = select(FD_SETSIZE, &set, 0, 0, &tv); if(result == 0) { cout << "select - timeout" << endl; continue; } else if(result == -1) { cout << "select - error" << endl; continue; } cout << "select - ok" << endl; if(FD_ISSET(fd, &set)) { int bytes = 0; ioctl(fd, FIONREAD, &bytes); cout << "bytes = " << bytes << endl; const int buf_size = 10; char buffer[buf_size+1]; while(bytes > 0) { int bytes2read = (bytes < buf_size) ? bytes : buf_size; int bytes_read = read(fd, buffer, bytes2read); if(bytes_read <= 0) { cerr << "ERROR: bytes_read is negative!" << endl; } else { buffer[bytes_read] = 0; cout << "READ: " << bytes_read << " - \"" << buffer << "\"" << endl; bytes -= bytes_read; } } } } cerr << "ERROR: this should never happen!" << endl; } void pipe_msg(int fd, const char *data) { int len = strlen(data); int bytes = write(fd, data, len); cout << "wrote " << bytes << " bytes to pipe" << endl; } int main() { cout << "enter" << endl; int pipes[2]; if(pipe(pipes)) { cerr << "ERROR: cannot create pipe!" << endl; exit(-1); } pthread_t thread; typedef void *(*THREAD_HOOK)(void *); ThreadArgument arg; arg.fd = pipes[0]; int res = pthread_create( &thread, 0, reinterpret_cast(&my_thread), &arg ); if(res) { cerr << "ERROR: cannot spawn thread!" << endl; exit(-1); } cout << "press a key to send data into pipe" << endl; cin.get(); pipe_msg(pipes[1], "A message from ruby to c++"); cin.get(); pipe_msg(pipes[1], "Ruby rocks! C++ sux!"); cin.get(); cout << "leave" << endl; pthread_cancel(thread); // todo: is this safe ? raceconditions close(pipes[0]); close(pipes[1]); pthread_exit(0); } > -- Simon Strandgaard