Czech language

g++

Execute bash commands and running programs by c++


06.04.13

Download source code (1.6kB)

Example program execute
less
ls
bash commands
and show a konsole by command
konsole



#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int RunCommand(const char *strCommand)
{
	int iForkId, iStatus;
	iForkId = vfork();
	if (iForkId == 0)	// This is the child 
	{
		iStatus = execl("/bin/sh","sh","-c", strCommand, (char*) NULL);
		exit(iStatus);	// We must exit here, 
				// or we will have multiple
				// mainlines running...  
	}
	else if (iForkId > 0)	// Parent, no error
	{
		iStatus = 0;
	}
	else	// Parent, with error (iForkId == -1)
	{
		iStatus = -1;
	}
	return(iStatus);
} 

int main(int argc, char *argv[])
{
	int iNumProc = 0, iChildiStatus = 0, iStatus = 0, iDeadId = 0;
	int iExitFlag = 0;
	
	// Run less command and display this main.cpp file
	iStatus = RunCommand("less main.cpp");
	if (!iStatus)
		iNumProc++;
	// Show new konsole
	iStatus = RunCommand("konsole");
	if (!iStatus)
		iNumProc++;
	// Run ls command and list information about the files in currect directory
	iStatus = RunCommand("ls -l");
	if (!iStatus)
		iNumProc++;
	
	
	// Wait till the commands complete
	while (iNumProc && !iExitFlag)
	{
		iDeadId = waitpid(-1, &iChildiStatus, WNOHANG);
		if (iDeadId < 0)
		{
			// Wait id error - exit the loop
			iExitFlag = 1;
		}
		else if (iDeadId > 0)
		{
			iNumProc--;
			// You can check the process exit iStatus here - its in the
			// iChildiStatus variable
		}
		else  // iDeadId == 0, no processes died
		{
			sleep(3);	// give them time to die
		}
	} 

	return 0;
}




home / g++


Valid XHTML 1.0 Transitional