Linux——gdb调试多进程和多线程

时间:2023-02-01 16:40:35

调试命令:
查询正在调试的进程:info inferiors
切换调试的进程: inferior
添加新的调试进程: add-inferior [-copies n] [-exec executable] , 可以用file executable来分配给inferior可执行文件。
其他:remove-inferiors infno, detach inferior

默认设置下,在调试多进程程序时GDB只会调试主进程。但是GDB(>V7.0)支持多进程的分别以及同时调试,换句话说,GDB可以同时调试多个程序。只需要设置follow-fork-mode(默认值:parent)和detach-on-fork(默认值:on)即可。
follow-fork-mode detach-on-fork 说明
parent on 只调试主进程(GDB默认)
child on 只调试子进程
parent off 同时调试两个进程,gdb跟主进程,子进程block在fork位置
child off 同时调试两个进程,gdb跟子进程,主进程block在fork位置
设置方法:set follow-fork-mode [parent|child] set detach-on-fork [on|off]

GDB默认支持调试多线程,跟主线程,子线程block在create thread。
查询线程:info threads
切换调试线程:thread

测试用例:

#include <stdio.h> 
#include <pthread.h>

void processA();
void processB();
void * processAworker(void *arg);

int main(int argc, const char *argv[])
{
int pid;
pid = fork();
if(pid != 0)
processA();
else
processB();
return 0;
}

void processA()
{
pid_t pid = getpid();
char prefix[] = "ProcessA: ";
char tprefix[] = "thread ";
int tstatus;
pthread_t pt;

printf("%s%lu %s\n", prefix, pid, "step1");

tstatus = pthread_create(&pt, NULL, processAworker, NULL);
if( tstatus != 0 )
{
printf("ProcessA: Can not create new thread.");
}

processAworker(NULL);
sleep(1);
}

void * processAworker(void *arg)
{
pid_t pid = getpid();
pthread_t tid = pthread_self();
char prefix[] = "ProcessA: ";
char tprefix[] = "thread ";

printf("%s%lu %s%lu %s\n", prefix, pid, tprefix, tid, "step2");
printf("%s%lu %s%lu %s\n", prefix, pid, tprefix, tid, "step3");

return NULL;
}

void processB()
{
pid_t pid = getpid();
char prefix[] = "ProcessB: ";
printf("%s%lu %s\n", prefix, pid, "step1");
printf("%s%lu %s\n", prefix, pid, "step2");
printf("%s%lu %s\n", prefix, pid, "step3");
}