linux - Returning output from bash script to calling C++ function -


i writing baby program practice. trying accomplish simple little gui displays services (for linux); buttons start, stop, enable, , disable services (much msconfig application "services" tab in windows). using c++ qt creator on fedora 21.

i want create gui c++, , populating gui list of services calling bash scripts, , calling bash scripts on button clicks appropriate action (enable, disable, etc.)

but when c++ gui calls bash script (using system("path/to/script.sh")) return value exit success. how receive output of script itself, can in turn use display on gui?

for conceptual example: if trying display output of (systemctl --type service | cut -d " " -f 1) gui have created in c++, how go doing that? correct way trying accomplish? if not,

  1. what right way? and
  2. is there still way using current method?

i have looked solution problem can't find information on how return values from bash to c++, how call bash scripts c++.

we're going take advantage of popen function, here.

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; } 

this function takes command argument, , returns output string.

note: not capture stderr! quick , easy workaround redirect stderr stdout, 2>&1 @ end of command.

here documentation on popen. happy coding :)


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -