如何检查Linux线程的状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9577231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:00:32  来源:igfitidea点击:

How to check the state of Linux threads?

linuxmultithreading

提问by user1251216

How could I check the state of a Linux threads using codes, not tools? I want to know if a thread is running, blocked on a lock, or asleep for some other reason. I know the Linux tool "top" could do this work. But how to implement it in my own codes. Thanks.

如何使用代码而不是工具检查 Linux 线程的状态?我想知道线程是否正在运行、被锁阻塞或由于其他原因睡着了。我知道 Linux 工具“top”可以完成这项工作。但是如何在我自己的代码中实现它。谢谢。

回答by Basile Starynkevitch

I think you should study in details the /procfile system, also documented here, inside kernel source tree.

我认为您应该详细研究/proc文件系统,这里也记录在 kernel source tree 中

It is the way the Linux kernel tells things to outside!

这是 Linux 内核向外界传达信息的方式!

There is a libprocalso (used by psand top, which reads /proc/pseudo-files).

还有一个libproc(由psand 使用top,它读取/proc/伪文件)。

See this question, related to yours.

看到这个问题,与你的有关。

Reading files under /proc/don't do any disk I/O (because /proc/is a pseudo file system), so goes fast.

读取下的文件/proc/不做任何磁盘 I/O(因为/proc/是一个伪文件系统),所以速度很快。

回答by RRM

Lets say your process id is 100.

假设您的进程 ID 是 100。

Go to /proc/100/taskdirectory and there you could see multiple directories representing each threads.

转到/proc/100/task目录,在那里您可以看到代表每个线程的多个目录。

then inside each subdirectory e.g. /proc/100/task/10100there is a file named status.

然后在每个子目录中,例如/proc/100/task/10100有一个名为status.

the 2nd line inside this file is the state information of the thread.

该文件中的第二行是线程的状态信息。

回答by Umut

You could also find it with by looking at the cgroup hierarchy of the service that your process belongs. Cgroups have a file called "tasks" and this file lists all the tasks of a service.

您还可以通过查看您的进程所属服务的 cgroup 层次结构来找到它。Cgroups 有一个名为“tasks”的文件,这个文件列出了一个服务的所有任务。

For example:

例如:

cat /sys/fs/cgroup/systemd/system.slice/hello.service/tasks

cat /sys/fs/cgroup/systemd/system.slice/hello.service/tasks

Note: cgroup should be enabled in your linux kernel.

注意:应该在您的 linux 内核中启用 cgroup。