JohnH
JohnH

Reputation: 150

get basic hardware information using C/C++/Java

I am trying to read some basic information about the device (in Solaris machine) like no. of CPUs, no. of HDDs, no. of Network adapters etc ...

From what I understand, we cannot get these information directly from Java. (Correct me if I am wrong).

So, the workaround is by calling JNI calls.

Now, how do I code this in C/C++ ? Is there any existing system call/ method in C to get these information ?

I am trying to avoid using system() method in C because I want to store the information as a string.

I am aware that there are shell commands like iostat, kstat, ifconfig etc ... But how do I simulate them in my C/C++ program ?

Thanks,

Upvotes: 0

Views: 2395

Answers (3)

Rob Hruska
Rob Hruska

Reputation: 120376

For a Java solution, an alternative to JNI would be to use Java's Runtime.exec() to execute system commands. Here's a simple example:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("/bin/cat /proc/cpuinfo");
process.waitFor();

InputStream in = process.getInputStream();
// read stdout contents from InputStream and parse accordingly

Note that this has disadvantages:

  • It is not platform-independent
  • Runtime.exec() has some gotchas it forks a child process to execute the command. In certain environments it will allocate as much memory to the forked process as the application invoking Runtime.exec() is using. According to this answer, it's because fork() duplicates the parent process when forking the child. This can be problematic for applications that use a lot of memory.

Upvotes: 1

Daniel
Daniel

Reputation: 28094

The /proc filesystem has lots of information for you to parse. iostat e.g. reads /proc/diskstats. There is much more there, and most of linuxs utilitiy programs just read the information from here.

You don't even need JNI to get all the info, at least, if you stay on linux or solaris.

Upvotes: 1

Edwin Buck
Edwin Buck

Reputation: 70949

To code this in JNI (bound to C)

  1. Write the Java class, with at least one method marked as "native".
  2. Use javac to compile the ".java" file to a ".class" file
  3. Use the javah tool to extract a C / C++ compatible header file from the compiled ".class" file.
  4. Write the C / C++ implementation for all the methods in the extracted header file, and compile them into a shared object library (.so for unix / linux, .dll for windows).
  5. Modify the original java source code to statically load the shared object library before any instances are created.

As far as how you can get the desired data, refer to any number of systems programming references for Windows or UNIX. If targeting the Linux platform, most of the tools are open source, so you can look at the source code to determine how the tools obtained their data (assuming that you can live with the license restrictions that such a task might place on your code).

Upvotes: 0

Related Questions