执行一次后如何停止顶级终端代码?

时间:2019-04-24 14:45:36

标签: java ubuntu terminal

我想查看一台机器的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

顶部命令输出

问题:

  1. 如果我首先启动“ top”命令,它并不会执行其他命令。
  2. 如此代码所示,当我首先启动Thread时,它显示“ TERM环境变量未设置”。
  3. 如果可能的话,将其直接存储在文本文件中,而不是在Java代码中读取和存储它。
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]

0 个答案:

没有答案