2

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
  • 2
    It's helpful to mention that you're calling it from java
    – Jeff Schaller
    Commented Aug 23, 2016 at 18:35
  • then why don't use other tools like ps, reading procfs...?
    – phuclv
    Commented Aug 24, 2016 at 5:00

1 Answer 1

12

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
  • 1
    Also, note that top needs at least two iterations to get CPU percentages correctly.
    – terdon
    Commented Aug 23, 2016 at 23:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .