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?

1
  • lsof lists open files so it would not provide you with the threads
    – joseph
    Sep 30, 2021 at 1:01

3 Answers 3

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.

3
  • (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) Jun 30, 2017 at 6: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= <pid>. Jun 30, 2017 at 6: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, 2017 at 12:48
3

This also works:

ps M <pid> | wc -l
1
  • As discussed in the comments under jweyrich’s answer, 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? Jun 30, 2017 at 16:20
2

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"

You must log in to answer this question.

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