Skip to content

Instantly share code, notes, and snippets.

@robotconscience
Last active October 8, 2017 21:49
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robotconscience/2554110 to your computer and use it in GitHub Desktop.
Save robotconscience/2554110 to your computer and use it in GitHub Desktop.
openFrameworks threaded system command caller with output
//
// SysCommand.h
//
// Created by Brett Renfer on 2/22/12.
//
#pragma once
#include "ofThread.h"
class SysCommand : private ofThread
{
public:
ofEvent<string> commandComplete;
void callCommand( string command ){
cmd = command;
stopThread();
startThread();
}
// CALL THIS DIRECTLY FOR BLOCKING COMMAND
// thanks to: http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
private:
void threadedFunction(){
ofLog( OF_LOG_VERBOSE, "call "+cmd );
string result = exec( (char *) cmd.c_str() );
ofLog( OF_LOG_VERBOSE, "RESULT "+result );
stopThread();
ofNotifyEvent( commandComplete, result, this );
}
string cmd;
};
Copy link

ghost commented Sep 10, 2012

Hi,

I'm new to this kind of things...
How can I use this class inside my code?
Thanks in advance,

Paulo Trigueiros

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