The command line in Linux is so incredibly powerful with so many functions available to you via the OS and optional applications you can install.  It is often the easiest solution in C++ programs to just use the command line to achieve something you need doing rather than finding a harder way to do it in code and the following examples let you do just that.

#include <stdlib.h>
	//Console command:
	system("cp file.x newfile.x");

	//Execute file:
	execlp("/usr/bin/omxplayer", " ", "/home/pi/projects/game/audio/alpha.wav", NULL);		//Execute file: file, arguments (1 or more strings followed by NULL - omxplayer has [OPTIONS] [FILE] hence the blank string)

System Function (Calling shell)

#include <stdlib.h>


	system("cp file.x newfile.x");

Call On A Background Thread

Can you get away with just adding a ‘&’ to the end of the line to cause it to be done in the background?  If not:

#include <unistd.h>
	int pid;
	pid=fork();
	if(pid==0)
	{
		//printf("I am the child\n");
		execlp("/usr/bin/omxplayer", " ", "/home/pi/projects/game/audio/alpha.wav", NULL);		//Execute file: file, arguments (1 or more strings followed by NULL - omxplayer has [OPTIONS] [FILE] hence the blank string)
		_exit(0);
	}
	else
	{
		//printf("I am the parent\n");
		wait();
	} 

Running as a different root user

If your application has been run as root user with sudo because you are using the IO pins you may want to make command lines calls as the standard pi user.  You can change to a different user using su – USERNAME -c before the command and surrounding it with quotes.

	system("su - pi -c \"fetchmail > /dev/null\"");

Getting The Result Of An Executed Console Command

#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;    //Or use std::string;

//************************************************************
//************************************************************
//********** EXECUTE CONSOLE COMMAND AND GET RESULT **********
//************************************************************
//************************************************************
//Note, this will return the output stdout. Some commands may generate a stderr response instead of stdout which you'd see on the console but this won't
//return, unless you simply add " 2>&1" to the end of your command string.  Then you'll get the output of stdout and stderr
string do_console_command_get_result (char* command)
{
	FILE* pipe = popen(command, "r");		//Send the command, popen exits immediately
	if (!pipe)
		return "ERROR";
	
	char buffer[128];
	string result = "";
	while(!feof(pipe))						//Wait for the output resulting from the command
	{
		if(fgets(buffer, 128, pipe) != NULL)
			result += buffer;
	}
	pclose(pipe);
	return(result);
}
If you want to run a command / tool that will run continuously

Use this example here

Getting The Result Of An Executed Console Command – In The Background

#include <string>
#include <iostream>
#include <stdio.h>
#include <fcntl.h>
using namespace std;    //Or use std::string;


//******************************************************************
//********** EXECUTE CONSOLE COMMAND AND GET RESULT ASYNC **********
//******************************************************************

static FILE* pipe;
static string result;
char buffer[128];

	switch (my_state_machine)
	{
		case start_request:
			//----- START THE REQUEST -----

			//Note, this will return the output stdout. Some commands may generate a stderr response instead of stdout which you'd see on the console but this won't
			//return, unless you simply add " 2>&1" to the end of your command string.  Then you'll get the output of stdout and stderr
			pipe = popen("wget -qO- \"mydomain.com/something.php\"", "r");		//Send the command, popen exits immediately
			if (!pipe)
			{
				cout << "ERROR" << endl;
				break;
			}
			//Set flags so fgets becomes non blocking
			int file_descriptor = fileno(pipe);
			int flags = fcntl(file_descriptor, F_GETFL, 0);
			flags |= O_NONBLOCK;
			fcntl(file_descriptor, F_SETFL, flags);

			result = "";

			my_state_machine = waiting_for_response;
			break;


		case waiting_for_response:
			//----- WAITING FOR RESPONSE -----

			while(fgets(buffer, sizeof(buffer), pipe) != NULL)
			{
				result += buffer;
			}

			if (feof(pipe))
			{
				cout << "Complete: " << result << endl;
				pclose(pipe);
				my_state_machine = idle;
				break;
			}
					
	}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published.