Sunday, December 17, 2006

Your own uname!

Adding another simple code to find some basic system information on Linux/Unix machines.
There are some API's, you will need to do some input parsing, which you can add to make this act as your own "uname" command!!

I have not added those to keep the code clean and simple....KISS - "Keep It Simple Stupid"



#include "sys/utsname.h"
#include "iostream"
#include "stdlib.h"

int main()
{
struct utsname name; // Structure to hold the system info.

if(uname(&name)==-1){
perror("System error:: ");
return -1;
}
cout << "sysname == " << name.sysname <<
" release == " << name.release <<
" version == " << name.version <<
" machine == " << name.machine <<
endl;
return 0;
}

NOTE : The above code compiles under Linux/Unix for sure. Have not tested on other platforms...


Here are the functions I wrote for parsing the input string....You can use them if you want
CALLING PI is : parse_argv(argc, argv, name); // You will have to add this in main after the if{}

template < class T>
void
printErr(T str_ch)
{
cout << "Invalid option..." << str_ch <<
"\tUsage: uname [-m][-r][-v][-s]" << endl;
}

void
parse_argv(int argc, char** argv, const utsname& sysinfo)
{
while(--argc) { // Check arguments supplied or not as argc == 1 imp no args
char* str = *(argv+ argc);
if('-' == *str ) { // - imp option specifed or not
while( *++str ) {
switch( *str )
{
case 's': cout << " System == " << sysinfo.sysname << endl; break;
case 'm': cout << " Machine == " << sysinfo.machine << endl; break;
case 'v': cout << " Version == " << sysinfo.version << endl; break;
case 'r': cout << " Release == " << sysinfo.release << endl; break;
default : printErr(*str);
}
}
} else {
printErr(*(argv + argc));
}
}
}

No comments: