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");.
1 Answer
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).
- 
        1Also, note thattopneeds at least two iterations to get CPU percentages correctly.2016-08-23 23:14:36 +00:00Commented Aug 23, 2016 at 23:14

ps, reading procfs...?