Skip to content

Instantly share code, notes, and snippets.

@rc1
Created April 29, 2015 17:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rc1/97c3e88298a9a9341e6e to your computer and use it in GitHub Desktop.
Save rc1/97c3e88298a9a9341e6e to your computer and use it in GitHub Desktop.
Non-blocking stdin reading in openFrameworks
#include "ThreadedCin.h"
#pragma mark - Lifecycle
ThreadedCin::ThreadedCin () {
latest = "";
}
ThreadedCin::~ThreadedCin () {
stopThread();
}
#pragma mark - Threads
void ThreadedCin::threadedFunction () {
int cnt;
while( isThreadRunning() && !feof( stdin ) ) {
cnt = read( STDIN_FILENO, buffer, sizeof buffer );
// Remove new line
buffer[ std::strcspn( buffer, "\n" ) ] = '\0';
ofLogNotice() << cnt;
ofLogNotice() << buffer;
lock();
latest = string( buffer );
unlock();
}
}
string ThreadedCin::getLatest () {
string result;
lock();
result = latest;
unlock();
return result;
}
void ThreadedCin::reset () {
lock();
latest = "";
unlock();
}
#pragma once
#include "ofMain.h"
class ThreadedCin : public ofThread {
public:
// # Lifecycle
ThreadedCin ();
virtual ~ThreadedCin ();
// # Threads
void threadedFunction();
string getLatest();
void reset();
private:
char buffer[ 8192 ];
string latest;
};
@SFR75
Copy link

SFR75 commented Oct 7, 2016

Hello,

I'm trying to understand how to integrate this snippet into openFramework code. I basically need to read STDIN and pass data to openFramework. Do I understand correctly that this code needs to be started in a thread and it should work this way ? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment