Created
April 29, 2015 17:39
-
-
Save rc1/97c3e88298a9a9341e6e to your computer and use it in GitHub Desktop.
Non-blocking stdin reading in openFrameworks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!