Scheduled Maintenance: We are aware of an issue with Google, AOL, and Yahoo services as email providers which are blocking new registrations. We are trying to fix the issue and we have several internal and external support tickets in process to resolve the issue. Please see: viewtopic.php?t=158230

 

 

 

pipes in C++ - examples

Programming languages, Coding, Executables, Package Creation, and Scripting.
Post Reply
Message
Author
User avatar
pychi
Posts: 26
Joined: 2014-12-24 23:04
Location: Dominican Republic

pipes in C++ - examples

#1 Post by pychi »

Hi, i need many examples of pipes in C++.
programs that capture external process from the shell etc etc.


anyone uses FLTK Library??

User avatar
edbarx
Posts: 5401
Joined: 2007-07-18 06:19
Location: 35° 50 N, 14 º 35 E
Been thanked: 2 times

Re: pipes in C++ - examples

#2 Post by edbarx »

I did something like this, if it may help.

Code: Select all

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <math.h>
#include <vector>
#include <unistd.h>
#include <readline/readline.h>


using namespace std;

/*


1) Glib::spawn_sync instead of a pipe stream, provides a slot.
2) cmd trying to call an inexistent command still returns a valid pointer!
   verify cmd exists before calling exec
*/

inline bool file_exists(const string& name) {
  return (access(name.c_str(), F_OK) != -1);
}

bool cmd_exists(string cmd)
{
  string cmd0 = cmd.substr(0, cmd.find(" "));
	string pth = getenv("PATH");
	string tmp_path = "";
	
	for (int i = 0; i < pth.length(); i++)
	{
	  if (pth[i] == ':' || i == pth.length() - 1)
		{		 
		  if (i == pth.length() - 1 && pth[i] != ':')
			   tmp_path += pth[i];
		  if (file_exists(tmp_path + "/" + cmd0))
			  return true;
				else tmp_path = "";
		}
		else tmp_path += pth[i];	
	}
	
  return false;
}

void flush_all_open_output_streams()
{
  fflush(NULL);
}

int exec(const char* cmd, vector<string> &out)
{
    const int buf_size = 128;
		
    FILE * pipe = popen(cmd, "r");
		char buffer[buf_size];
		while(!feof(pipe)) {
    	if(fgets(buffer, buf_size, pipe) != NULL)
    		out.push_back(buffer);
    }
		
		return pclose(pipe);
}

int main ()
{
  //system("ls -l /");
	vector<string> output;
	string cmd;
	cmd = readline("command to execute ?: ");
	
	if (cmd_exists(cmd))
  { 
	  exec(cmd.c_str(), output);
	  for (int i; i < output.size(); i++)
	    cout << output[i];
	}
	else cout << "command does not exist\n";		
	
  return 0;
}
Debian == { > 30, 000 packages }; Debian != systemd
The worst infection of all, is a false sense of security!
It is hard to get away from CLI tools.

Post Reply