Skip to content

Instantly share code, notes, and snippets.

@rc1
Created Apr 29, 2015
Embed
What would you like to do?
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