6

I'd like to be able to get the number of thread per process in command-line and get the exact same number I can see via the Activity Monitor.

At the moment the IntelliJ IDEA process (PID 5235) has 266 Thread. I'd like to get this number but via a command line.

I've tried

lsof -p 5235 | wc -l

Any suggestions?

TheEwook
  • 178
  • 1
  • 1
  • 5

3 Answers3

13

Try the following:

NUM=`ps M <pid> | wc -l` && echo $((NUM-1))

We subtract 1 from the line count because ps outputs a HEADER in the 1st line.

jweyrich
  • 1,296
  • 1
  • 12
  • 14
  • (1) The output from `wc -l` is a single “word”; i.e., a (*single* ) non-null sequence of non-blank characters, possibly preceded and/or followed by whitespace.  What do you gain by piping it into `xargs`?  (I.e., won’t your command do the same thing if you leave off the `| xargs`?)  Are you doing it just to strip the leading and/or trailing whitespace?  Why bother?  `expr` will take care of that for you.   … (Cont’d) – Scott - Слава Україні Jun 30 '17 at 06:49
  • (Cont’d) …  (2) Why are you subtracting one?  To exclude the header line from the count?  Good answers explain things like that. (3) I suppose using `expr` is OK, but it might be better to say `NUM=$((NUM-1))` or `((NUM--))`. Or you could just suppress the header by saying `ps M -opid= `. – Scott - Слава Україні Jun 30 '17 at 06:50
  • @Scott: you're absolutely right. I did update the answer to include the your improvements. Thank you! The only thing I didn't include was the `-opid=` because it doesn't seem to work on macOS. If you still feel it could be better, feel free to update it or just leave another comment. – jweyrich Jun 30 '17 at 12:48
3

This also works:

ps M <pid> | wc -l
Greenonline
  • 2,235
  • 11
  • 24
  • 30
giraysam
  • 131
  • 2
  • As discussed in the comments under [jweyrich’s answer](https://superuser.com/q/753682/150988#753707), this will be too high by one, because it will count the `ps` header line.  Or do you have a rationale for believing that your answer is correct? – Scott - Слава Україні Jun 30 '17 at 16:20
1

One can also engage tail command in order to cut off header line in the ps M output, e.g:

ps M <pid> | tail -n+2 | wc -l

where -n+2 option means "get all lines starting from the second one"

ghost28147
  • 141
  • 2