根据
/proc/[pid]/stack(自Linux 2.6.29起)提供了该进程内核栈中函数调用的符号跟踪。仅当内核使用CONFIG_STACKTRACE配置选项构建时,才提供此文件。
因此我编写了一个测试程序:
proc
手册:/proc/[pid]/stack(自Linux 2.6.29起)提供了该进程内核栈中函数调用的符号跟踪。仅当内核使用CONFIG_STACKTRACE配置选项构建时,才提供此文件。
因此我编写了一个测试程序:
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <pthread.h>
void *thread_func(void *p_arg)
{
pid_t pid = fork();
if (pid > 0) {
wait(NULL);
return 0;
} else if (pid == 0) {
sleep(1000);
return 0;
}
return NULL;
}
int main(void)
{
pthread_t t1, t2;
pthread_create(&t1, NULL, thread_func, "Thread 1");
pthread_create(&t2, NULL, thread_func, "Thread 2");
sleep(1000);
return 0;
}
运行后,使用pstack
检查进程的线程:
linux-uibj:~ # pstack 24976
Thread 3 (Thread 0x7fd6e4ed5700 (LWP 24977)):
#0 0x00007fd6e528d3f4 in wait () from /lib64/libpthread.so.0
#1 0x0000000000400744 in thread_func ()
#2 0x00007fd6e52860a4 in start_thread () from /lib64/libpthread.so.0
#3 0x00007fd6e4fbb7fd in clone () from /lib64/libc.so.6
Thread 2 (Thread 0x7fd6e46d4700 (LWP 24978)):
#0 0x00007fd6e528d3f4 in wait () from /lib64/libpthread.so.0
#1 0x0000000000400744 in thread_func ()
#2 0x00007fd6e52860a4 in start_thread () from /lib64/libpthread.so.0
#3 0x00007fd6e4fbb7fd in clone () from /lib64/libc.so.6
Thread 1 (Thread 0x7fd6e569f700 (LWP 24976)):
#0 0x00007fd6e4f8d6cd in nanosleep () from /lib64/libc.so.6
#1 0x00007fd6e4f8d564 in sleep () from /lib64/libc.so.6
#2 0x00000000004007b1 in main ()
同时,检查 /proc/24976/stack
:
linux-uibj:~ # cat /proc/24976/stack
[<ffffffff804ba1a7>] system_call_fastpath+0x16/0x1b
[<00007fd6e4f8d6cd>] 0x7fd6e4f8d6cd
[<ffffffffffffffff>] 0xffffffffffffffff
24976
进程有3
个线程,它们都在系统调用(nanosleep
和wait
)上被阻塞,所以现在所有的3
个线程都在kernel
空间中工作,并且成为了内核线程,是吗?如果是这样,那么/proc/[pid]/stack
文件中应该有3
个栈。但是看起来在/proc/[pid]/stack
文件中只有一个栈。
我应该如何理解/proc/[pid]/stack
?
/proc/[tid]/stack
将获取线程的内核栈信息,或者使用/proc/[pid]/task/[tid]/stack
。 - Nan Xiao