请考虑以下程序。
#include <unistd.h>
int main(){
sleep(1000);
}
如果我们在此程序上运行strace
,则长时间睡眠之前出现的最后一行如下。
nanosleep({1000, 0},
当程序处于睡眠状态时,代码正在操作系统内核内执行(可能被阻止(。
当我在gdb
下运行程序时,如果我在睡眠中发送SIGINT
,我可以收集有关主线程的各种信息,例如其backtrace
和各种寄存器值。
gdb 中是否有一些表达式计算结果为true
线程在再次在用户空间中执行代码之前必须越过syscall
边界?
理想情况下,将有一个跨平台的解决方案,但特定于平台的解决方案也很有用。
澄清:我不关心线程是否实际执行;只关心它最近的程序计数器值是在内核代码还是用户代码中。
换句话说,gdb
能告诉我们某个线程是否已经进入内核但尚未退出内核吗?
gdb 中是否有一些表达式计算结果为 true,如果 线程在执行代码之前必须跨越系统调用边界 又是用户空间?
您可以尝试使用catch syscall nanosleep
,请参阅文档。
catch syscall nanosleep
停止在 2 个事件上:一个在呼叫系统调用时,另一个在从系统调用返回时停止。您可以使用info breakpoints
来查看此捕获点的命中次数。如果它是偶数,那么您应该在用户空间中。如果它很奇怪,那么你应该在内核空间中:
$ gdb -q a.out
Reading symbols from a.out...done.
(gdb) catch syscall nanosleep
Catchpoint 1 (syscall 'nanosleep' [35])
(gdb) i b
Num Type Disp Enb Address What
1 catchpoint keep y syscall "nanosleep"
(gdb) r
Starting program: /home/ks1322/a.out
Missing separate debuginfos, use: dnf debuginfo-install glibc-2.27-8.fc28.x86_64
Catchpoint 1 (call to syscall nanosleep), 0x00007ffff7adeb54 in nanosleep () from /lib64/libc.so.6
(gdb) i b
Num Type Disp Enb Address What
1 catchpoint keep y syscall "nanosleep"
catchpoint already hit 1 time
(gdb) c
Continuing.
Catchpoint 1 (returned from syscall nanosleep), 0x00007ffff7adeb54 in nanosleep () from /lib64/libc.so.6
(gdb) i b
Num Type Disp Enb Address What
1 catchpoint keep y syscall "nanosleep"
catchpoint already hit 2 times
(gdb) c
Continuing.
[Inferior 1 (process 19515) exited normally]