3

How to identify a thread is a kernel thread or not through bash?

I found that you could identify the kernel thread by ps: if the thread name is enclosed in [], it's a kernel thread. But i do not think it is a good solution.

I would be thankful for any hint on this question.

2
  • 1
    Welcome to Stack Overflow. SO is a question and answer page for professional and enthusiastic programmers. Add your own code to your question. You are expected to show at least the amount of research you have put into solving this question yourself. Commented May 21, 2020 at 13:29
  • I would follow your advice. Commented May 21, 2020 at 13:31

1 Answer 1

4

You can determine whether a particular task is a kthread or not by looking at /proc/<PID>/stat. More presicesely, according to man 5 proc the 9th field of this virtual file contains the kernel flags for the process. In case of a kthread, the flags will have PF_KTHREAD set.

Here's an example of a Bash script that takes a PID as argument and checks if it's a kthread or not:

#!/bin/bash

read -a stats < /proc/$1/stat
flags=${stats[8]}

if (( ($flags & 0x00200000) == 0x00200000 )); then
    echo 'KTHREAD'
else
    echo 'NOT KTHREAD'
fi

This isn't really simpler than just doing ps u -p <PID> and checking for [], but it's a pure Bash solution nonetheless.


There are also some more "tricks" which can be used to identify a kernel thread, it's easy to modify the above script to use one of the methods highlighted in this post.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.