I want to execute the top command just one iteration, so I can capture the process output programmatically. If I just execute top, it won't return unless I kill the terminal. Thus, I only need to execute it once and return. How can I do it?
Edit: I'm running the top command from Java: Runtime.getRuntime().exec("top");.

  • 2
    It's helpful to mention that you're calling it from java – Jeff Schaller Aug 23 '16 at 18:35
  • then why don't use other tools like ps, reading procfs...? – phuclv Aug 24 '16 at 5:00

As least with Linux/procps top you probably want both -b (to switch it to batch mode) and -n 1 (to only run one iteration).

top -b -n 1

I suggest reading the manual page via man top, it documents these options.

Not to mention, depending on the goal, there may be better tools to use (e.g., ps or some library available in your programming language).

  • 1
    Also, note that top needs at least two iterations to get CPU percentages correctly. – terdon Aug 23 '16 at 23:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.