-1

I have this code:

String command = "dmidecode -t2";   

try {
        Process pb = new ProcessBuilder("/bin/bash", "-c", command).start();
    } 
catch (IOException e) {
    e.printStackTrace();
}

I want to save the output of the command to RAM (so I can use it only in real time). How can I save the output to a string in RAM?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
toto gam
  • 1
  • 1
  • Possible duplicate of [Java: popen()-like function?](http://stackoverflow.com/questions/2887658/java-popen-like-function) – ceving May 03 '17 at 15:22

2 Answers2

0

All relevant streams are available using one of Process#getOutputStream(), Process#getInputStream(), Process#getErrorStream().

You should not care if they are saved in RAM or not: you can read stdout while the process is still running.

dfogni
  • 763
  • 9
  • 14
-1

You can use class sun.misc.Unsafe, that lets you work with the JVM memory directly.
Its constructor is private, So you can get an Unsafe instance like this:

public static Unsafe getUnsafe() {
    try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            return (Unsafe)f.get(null);
    } catch (Exception e) { /* ... */ }
}

You can then get your string bytes with:

 byte[] value = []<your_string>.getBytes()
 long size = value.length

You can now allocate the memory size and write the string in RAM:

long address = getUnsafe().allocateMemory(size);
getUnsafe().copyMemory(
            <your_string>,      // source object
            0,              // source offset is zero - copy an entire object
            null,           // destination is specified by absolute address, so destination object is null
            address, // destination address
            size
); 
// the string was copied to off-heap 

Source: https://highlyscalable.wordpress.com/2012/02/02/direct-memory-access-in-java/

Andrea Rossi
  • 981
  • 1
  • 10
  • 23
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/15999083) – EJoshuaS - Stand with Ukraine May 01 '17 at 14:40
  • 1
    Oh, I didn't think about that possibility. Ok, i'm writing a new answer based on the content of that page. Thanks for the advice! – Andrea Rossi May 01 '17 at 15:49