david_1234
Posts: 200
Joined: Mon Jan 01, 2018 2:14 pm

Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 9:14 am

Hello ,
I'm having a strange problem
I'm trying to read the CPU load using this commnad:

Code: Select all

top -n1 | grep "%Cpu"
when I try to use this java code :

Code: Select all

 try 
        {
            ProcessBuilder GetCPU = new ProcessBuilder ("sudo" , top" ,"-n1","grep" , "%Cpu");
          //*2  ProcessBuilder GetCPU = new ProcessBuilder ("sudo" , sh" , "/home/pi/Desktop/CPU.sh");
            GetCPU.redirectErrorStream(true);
            Process CPU = GetCPU.start();
            BufferedReader CPUr = new BufferedReader (new InputStreamReader(CPU.getInputStream()));
            line = CPUr.readLine();
            System.out.println("CPU is - " + line);
        }
I'm geting this answer:

Code: Select all

CPU is - top: unknown option '|'
when I try to run a sh file using the same command (which work on cmd) - mark as *2 at the code
I'm getting this error:

Code: Select all

CPU is - 'unknown': I need something more specific.

what am I doing wrong ,what am I missing?

Thanks ,

User avatar
DougieLawson
Posts: 36540
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 9:51 am

You have to build two processes. One to run the top command. One to run the grep (although it may be more pythonic to use the python3 regex library rather than spawning a grep process).

You then do some plumbing to pipe the stdout from the top process to the stdin of the grep process.

http://queirozf.com/entries/python-3-su ... s-together
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

david_1234
Posts: 200
Joined: Mon Jan 01, 2018 2:14 pm

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 10:12 am

The problem is that the main code is JAVA and I need to keep the answer and do some work with the numbers

I don't want to start using python from java - I think it will complicate things - no ?

isn't better to use only 1 language?


Thanks ,

User avatar
DougieLawson
Posts: 36540
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 10:17 am

Sorry it's so rare to see a Java question on here, nobody uses Java.

Java has a regex library. Java has a way to pipe output from a subprocess to another process. Basically stop using grep.

Example #8 here: https://www.programcreek.com/java-api-e ... r.Redirect
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

User avatar
PeterO
Posts: 5133
Joined: Sun Jul 22, 2012 4:14 pm

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 10:32 am

Would it be easier to just read and parse /proc/stat ?
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

david_1234
Posts: 200
Joined: Mon Jan 01, 2018 2:14 pm

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 1:21 pm

I don't have this file \ library.
do I need to install something?

User avatar
DougieLawson
Posts: 36540
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 1:34 pm

david_1234 wrote:
Sun Nov 10, 2019 1:21 pm
I don't have this file \ library.
do I need to install something?
Eh? It's a virtual filesystem that's instantiated as part of booting the Linux kernel. Try cat /proc/stat from a LXTerminal.
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

david_1234
Posts: 200
Joined: Mon Jan 01, 2018 2:14 pm

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 2:05 pm

Ok
now I see it

but now what ?
this is what I ask here
https://www.raspberrypi.org/forums/view ... 7#p1562897

what do I need to calcualte in order to see the current CPU use?
I guess something from this line ?

Code: Select all

12705560 1075 1114248 131286844 258837 0 58030 0 0 0
if I take the 2nd value and devide it from the 1st one?
will this give me the CPU current use?

because when I do this I get 0.08 --> 8% and on the monitor I can see it's around 8 i

is this finally the answer?

Thanks ,

User avatar
DougieLawson
Posts: 36540
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 2:09 pm

Read the code for the top command. https://github.com/mmalecki/procps/blob/master/top.c
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

david_1234
Posts: 200
Joined: Mon Jan 01, 2018 2:14 pm

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 2:15 pm

you want me to read ~3100 lines of code? :-)
maybe you can point me to the answer ?

I can only assume you know the answer

Thanks ,

User avatar
PeterO
Posts: 5133
Joined: Sun Jul 22, 2012 4:14 pm

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 2:35 pm

google /proc/stat :roll:
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

david_1234
Posts: 200
Joined: Mon Jan 01, 2018 2:14 pm

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 3:24 pm

this is what I did for the last hour
finally made this solution according to this explain
https://supportcenter.checkpoint.com/su ... id=sk65143

Code: Select all

 String CpuFileName = "/proc/stat";
        String line = null;
        String strArray[] = new String[12];
        double CpuLoad = 0;
	
	try {

            FileReader fileReader1 = new FileReader(CpuFileName);
            BufferedReader bufferedReader1 = new BufferedReader(fileReader1);
            line = bufferedReader1.readLine (); //get only the first line 
            
            System.out.println(line);
             
            bufferedReader1.close(); //finish reading after the first line 
            
            strArray= line.split(" ");
                       
            double TotalCPU = 0;
            double IdleCPU = 100;
            
            for (int i=2 ; i<12 ; i++)
            {
            TotalCPU = TotalCPU + Integer.parseInt(strArray[i]); 
             }
            IdleCPU = Integer.parseInt(strArray[5]); //the palce of the idle 
            System.out.println("CPU Idle: " + IdleCPU);
            System.out.println ("Total is - " + TotalCPU);
            
            CpuLoad = (100 - ((IdleCPU / TotalCPU) * 100));
            
            System.out.println ("Current CPU use is - " + CpuLoad + "%");
            
            
    }

        catch(IOException ex) {
            System.out.println(ex);
        }
it's seem to work
I get only around 9% - and on the monitor I see also aroud 9%
I will try to run some things on the PI to see if this is working OK when CPU is working harder :-)


if you find something wrong in the code ( or mayeb thr logic of it ) - let me know



***** update
it's not working
I get the same value all the time , even when the monitor show much higher CPU load
Untitled.png
Untitled.png (95.77 KiB) Viewed 453 times


Thanks ,

User avatar
PeterO
Posts: 5133
Joined: Sun Jul 22, 2012 4:14 pm

Re: Unable to read cmd line from sh file using Java

Sun Nov 10, 2019 5:10 pm

You have not taken notice of this important piece of information....
http://www.linuxhowtos.org/System/procstat.htm wrote: "All of the numbers reported in this file are aggregates since the system first booted."
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

david_1234
Posts: 200
Joined: Mon Jan 01, 2018 2:14 pm

Re: Unable to read cmd line from sh file using Java

Mon Nov 11, 2019 8:34 am

So this doesn't help me to get to the solution I need either :|

I think Linux moto should be
"Let's make things more complicated....."

so maybe you have any idea how to get the cpu load (the same value I get in the monitor ) ?

Thanks ,

User avatar
PeterO
Posts: 5133
Joined: Sun Jul 22, 2012 4:14 pm

Re: Unable to read cmd line from sh file using Java

Mon Nov 11, 2019 8:47 am

david_1234 wrote:
Mon Nov 11, 2019 8:34 am
So this doesn't help me to get to the solution I need either :|

I think Linux moto should be
"Let's make things more complicated....."

so maybe you have any idea how to get the cpu load (the same value I get in the monitor ) ?

Thanks ,
I absolutely tells you how to get the data you want. Maybe you don't understand it, in which case ask more questions rather than that having a hissy fit and going off in a huff......

If you look closely at the numbers in /proc/stat you will see they only ever increase. You need to get a set of numbers (setA), wait a second and get another set of numbers (setB). Then subtract setA from SetB and it will give you the usage data for the last second. Then move setB to SetA, wait another second, get a new setB and subtract .... rinse and repeat !

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

david_1234
Posts: 200
Joined: Mon Jan 01, 2018 2:14 pm

Re: Unable to read cmd line from sh file using Java

Mon Nov 11, 2019 9:37 am

OK -
I can do this :-)

just to see I got it right
on t0 I have column1 , column2 , column3 ....
on t1 I have column1_1 , column2_1 , column3_1

then I sub columns1_1-column1 .....
I get a "new" line with 7 values\numbers
and from there I do waht I did before?

Code: Select all

CpuLoad = (100 - ((IdleCPU / TotalCPU) * 100));
?

did I understand you correctly?

Thanks ,

User avatar
PeterO
Posts: 5133
Joined: Sun Jul 22, 2012 4:14 pm

Re: Unable to read cmd line from sh file using Java

Mon Nov 11, 2019 9:39 am

Sounds reasonable.
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

david_1234
Posts: 200
Joined: Mon Jan 01, 2018 2:14 pm

Re: Unable to read cmd line from sh file using Java

Mon Nov 11, 2019 10:00 am

whould you do it different? (Logic speaking)
Thanks ,

User avatar
PeterO
Posts: 5133
Joined: Sun Jul 22, 2012 4:14 pm

Re: Unable to read cmd line from sh file using Java

Mon Nov 11, 2019 11:05 am

david_1234 wrote:
Mon Nov 11, 2019 10:00 am
whould you do it different? (Logic speaking)
Thanks ,
I wouldn't be doing it in Java for a start ! :D
I have a C/GTK3 version that drives a "Load Meter"
Meter3.png
Meter3.png (14.9 KiB) Viewed 370 times
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

User avatar
addeswe
Posts: 29
Joined: Fri Jul 19, 2013 3:49 pm
Location: Sweden

Re: Unable to read cmd line from sh file using Java

Thu Nov 14, 2019 8:40 am

Usually I don't really like to post bad code. However, I have no idea what you want to do with this. So I'll just show you an easy way to do it.

Code: Select all

		List<String> load = new ArrayList<String>();
		ProcessBuilder pb = new ProcessBuilder("uptime");
		Process p = pb.start();
		Pattern pattern = Pattern.compile("\\d\\.\\d\\d");
		String loads = new BufferedReader(new InputStreamReader(p.getInputStream())).readLine();
		Matcher match = pattern.matcher(loads);
		while (match.find()) {
			load.add(match.group());
		}
		System.out.println(load.get(0));
		System.out.println(load.get(1));
		System.out.println(load.get(2));
		// OR
		load.stream().forEach(e -> System.out.println(e));
“Knock, knock.” - “Who’s there?” - very long pause…. - “Java.”
If a python knocks on your door and says “Hi, I’m a vacuum cleaner!” it’s not true. That’s a python.

Return to “Java”