PDA

View Full Version : Coding using system commands




jmac555
Jun 4, 2008, 07:16 AM
As a small project i am testing the use of mac terminal commands with C++, I
have started with the basic ones (ps aux, telnet etc, etc). I was wondering if there was any way to include a user input in the command sent to the terminal , eg entering the PID of the program you want to kill. Just in case it helps the code i am using is posted below.

#include <iostream>

int main()
{
int proc;
int PID;
using namespace std;
cout << "Welcome to the terminal tool for the common idiot\n";
cout << "Please choose from the below options, which process you would like to perform";

while(1)
{
cout << "(1) Show all running process's, (2) Telnet options, (3) Send Mail, (4) Kill application\n";
cin >> proc;

if (proc==1)
{
system ("ps aux");

}

if (proc==2)
{
system ("telnet");
}

if (proc==3)
{
system ("MAIL TO:");
}

if (proc==4)
{
cout << "Enter PID (obtained via process 1)\n";
system ("kill") ;

}

else
{
cout << "that is not a valid response, please select an option from the menu\n";
}
}
}



fredthefool
Jun 4, 2008, 09:41 AM
a stringstream (#include<sstream>) is your friend: due to his overloaded <<-operators, you can write to and concatenate strings in the same manner you would 'stdout'. to get a real string out of the stream, use his str()-method. and get a c-string out of it for the system-command needs this form of param. there are helpful subclasses istringstream and ostringstream.


ostringstream os;
os << "YOUR_COMMAND " << param_string;
system((os.str()).c_str());


the param_string can be keyed in at runtime ("cin") or extracted from argv[].
(and it wouldn't be bad to catch the return value of the system-command in a if-condition)

jmac555
Jun 4, 2008, 06:55 PM
so should it now read?

#include <iostream>
#include <sstream>

int main()
{
int proc;
int PID;
using namespace std;
cout << "Welcome to the terminal tool for the common idiot\n";
cout << "Please choose from the below options, which process you would like to perform";

while(1)
{
cout << "(1) Show all running process's, (2) Telnet options, (3) Send Mail, (4) Kill application\n";
cin >> proc;

if (proc==1)
{
system ("ps aux");

}

if (proc==2)
{
system ("telnet");
}

if (proc==3)
{
system ("MAIL TO:");
}

if (proc==4)
{
cout << "Enter PID (obtained via process 1)\n";
cin >> PID;
ostringstream os;
os << system ("pause") << PID;
system((os.str()).c_str());

}

else
{
cout << "that is not a valid response, please select an option from the menu\n";
}
}
}

fredthefool
Jun 5, 2008, 09:12 AM
better try this part:


[ -- snip -- ]

if (proc=="4") //generally, keyboard input delivers a string, so i prefer this
{
cout << "Enter PID (obtained via process 1)" << endl;
cin >> PID;

ostringstream os;
os << "kill " << PID; // fill stringstream ...

// check return value of operating system -- 0 if OK;
if(system((os.str()).c_str())){
cerr << "Command failure" << endl;
}
}

[ -- snap -- ]