Last active
October 8, 2017 21:49
-
-
Save robotconscience/2554110 to your computer and use it in GitHub Desktop.
openFrameworks threaded system command caller with output
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
// | |
// 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I'm new to this kind of things...
How can I use this class inside my code?
Thanks in advance,
Paulo Trigueiros