我想查看一台机器的CPU和RAM利用率,直到我的Java代码运行为止。所以我使用了最高命令,但是我不知道如何以及何时停止它?
我不知道waitFor()
如何为我工作?
我可能会在线程中运行代码,但是如何告诉它等待该线程完成执行并停止呢?
MyCode
import...*;
public class MyCode {
ThreadSubclass thread1 = new ThreadSubclass();
thread1.start();
/*
I want Mycode to Run in parallel while top command stores output of RAM and CPU usage.
Can I write my code here??
When myCode is complete, stop Top command.
*/
System.out.println("0");
Process cmdProc = Runtime.getRuntime().exec("top");
System.out.println("1");
BufferedReader stdoutReader = new BufferedReader(
new InputStreamReader(cmdProc.getInputStream()));
String line;
while ((line = stdoutReader.readLine()) != null) {
// process procs standard output here
System.out.println(line);
}
System.out.println("2");
BufferedReader stderrReader = new BufferedReader(
new InputStreamReader(cmdProc.getErrorStream()));
while ((line = stderrReader.readLine()) != null) {
// process procs standard error here
System.out.println(line);
}
cmdProc = Runtime.getRuntime().exec("Ctrl+C");
}
在另一个文件中……ThreadSubclass.java
public class ThreadSubclass extends Thread {
@Override
public void run() {
//Should I write all my code here? I had used fork earlier and it gave me pid, so It was easier for me to run my code inside that if condition of fork pid.
System.out.println("ThreadSubclass is running");
}
}
当前输出:
0
ThreadSubclass正在运行
1
2
未设置TERM环境变量。
预期输出:
0
ThreadSubclass正在运行
1
2
顶部命令输出
问题:
Process cmdProc = Runtime.getRuntime().exec("top -b > Top.csv");
error =>
top: unknown option '>'
Usage:
top -hv | -bcHiOSs -d secs -n max -u|U user -p pid(s) -o field -w [cols]