Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying kernel threads

Tags:

linux

process

I'd like to know how I can distinguish a kernel-thread from a user-thread for a process-scanner I'm building. I'm having a hard time finding a good definition of both types.

I found that kernel-threads don't have memory of their own, so no Vm* values in /proc/$pid/status, and that a stat on /proc/$pid/exe does not return anything.

So, I figured I could identify kernel threads if a process has no Vm* values and no inode number. I figured wrong... my script sees php-cgi processes that are identified as kernel processes sometime.

If found that most of those wrongly identified processes are zombies that are gone a second later. So I implemented a simple check to see if the status is "Z". If so, ignore it. That saved me a lot of false positives, but still I receive messages about php-cgi kernel-processes.

Can anyone tell me how I can distinguish a kernel-thread from a user-thread the right way?

like image 206
HighKing Avatar asked Aug 31 '12 10:08

HighKing


1 Answers

There are some visible differences between a kernel thread and a user-space thread:

  • /proc/$pid/cmdline is empty for kernel threads - this is the method used by ps and top to distinguish kernel threads.

  • The /proc/$pid/exe symbolic link has no target for kernel threads - which makes sense since they do not have a corresponding executable on the filesystem.

    More specifically, the readlink() system call returns ENOENT ("No such file or directory"), despite the fact that the link itself exists, to denote the fact that the executable for this process does not exist (and never did).

    Therefore, a reliable way to check for kernel threads should be to call readlink() on /proc/$pid/exe and check its return code. If it succeeds then $pid is a user process. If it fails with ENOENT, then an extra stat() on /proc/$pid/exe should tell apart the case of a kernel thread from a process that has just terminated.

  • /proc/$pid/status is missing several fields for most kernel threads - more specifically a few fields related to virtual memory.

like image 85
thkala Avatar answered Oct 11 '22 14:10

thkala