首页 > 系统相关 >【gdb】调试子进程

【gdb】调试子进程

时间:2023-10-15 20:48:18浏览次数:38  
标签:fork pid gdb 进程 world hello 调试

调试子进程

1. 例子

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
  pid_t pid;

  pid = fork();
  if (pid < 0)
  {
    exit(1);
  }
  else if (pid > 0)
  {
    exit(0);
  }
  printf("hello world\n");
  return 0;
}

在调试多进程程序时,gdb默认会追踪父进程。例如:

(gdb) start
Temporary breakpoint 1 at 0x40055c: file a.c, line 8.
Starting program: /data2/home/nanxiao/a

Temporary breakpoint 1, main () at a.c:8
8               pid = fork();
(gdb) n
9               if (pid < 0)
(gdb) hello world

13              else if (pid > 0)
(gdb)
15                      exit(0);
(gdb)
[Inferior 1 (process 12786) exited normally]

可以看到程序执行到第15行:父进程退出。如果要调试子进程,要使用如下命令:“set follow-fork-mode child”,例如:

(gdb) set follow-fork-mode child
(gdb) start
Temporary breakpoint 1 at 0x40055c: file a.c, line 8.
Starting program: /data2/home/nanxiao/a

Temporary breakpoint 1, main () at a.c:8
8               pid = fork();
(gdb) n
[New process 12241]
[Switching to process 12241]
9               if (pid < 0)
(gdb)
13              else if (pid > 0)
(gdb)
17              printf("hello world\n");
(gdb)
hello world
18              return 0;

可以看到程序执行到第17行:子进程打印“hello world”。

这个命令目前Linux支持,其它很多操作系统都不支持,使用时请注意

 

参考资料

1. gdb手册

2. 调试子进程

标签:fork,pid,gdb,进程,world,hello,调试
From: https://www.cnblogs.com/sunbines/p/17766126.html

相关文章

  • 【gdb】调试已经运行的进程
     调试已经运行的进程1.例子:#include<stdio.h>#include<pthread.h>void*thread_func(void*p_arg){while(1){printf("%s\n",(char*)p_arg);sleep(10);}}intmain(void){pthread_tt1,t2;pthread_create(&t1,NULL,......
  • 【gdb】让catchpoint只触发一次
    让catchpoint只触发一次1.例子:#include<stdio.h>#include<stdlib.h>#include<sys/types.h>#include<unistd.h>intmain(void){pid_tpid;inti=0;for(i=0;i<2;i++){ pid=fork(); if(pid<0)......
  • 【gdb】打印内存的值
    打印内存的值1.例子#include<stdio.h>intmain(void){inti=0;chara[100];for(i=0;i<sizeof(a);i++){a[i]=i;}return0;}gdb中使用“x”命令来打印内存的值,格式为“x/nfuaddr”......
  • 【gdb】进入和退出图形化调试界面
    进入和退出图形化调试界面1.例子#include<stdio.h>voidfun1(void){inti=0;i++;i=i*2;printf("%d\n",i);}voidfun2(void){intj=0;fun1();j++;j=j*2;print......
  • 【gdb】打印数组的索引下标
    打印数组的索引下标1.例子#include<stdio.h>intnum[10]={1<<0,1<<1,1<<2,1<<3,1<<4,1<<5,1<<6,1<<7,1<<8,1<<9};intmain(void){inti;for......
  • 【gdb】gdb目录索引
    gdb目录索引 打印1打印ASCII和宽字符字符串打印数组中任意连续元素......
  • 【gdb】打印ASCII和宽字符字符串
    打印ASCII和宽字符字符串1.例子:#include<stdio.h>#include<wchar.h>intmain(void){charstr1[]="abcd";wchar_tstr2[]=L"abcd";return0;}用gdb调试程序时,可以使用“x/s”命令打印ASCII字符串。以上面程序为例:[root@node0......
  • 【gdb】设置观察点
    设置观察点1.例子:#include<stdio.h>#include<pthread.h>typedefstruct{inta;intb;intc;intd;pthread_mutex_tmutex;}ex_st;intmain(void){ex_stst={1,2,3,4,PTHREAD_MUTEX_INITIALIZER};printf("%d,%d,%d,%d\n&......
  • 进程的三态模型
        ......
  • 【gdb】run和start区别
    run和start区别gdb调试器提供了多种方式来启动目标程序,其中最常用的就是run指令,其次为start指令。也就是说,run和start指令都可以用来在gdb调试器中启动程序,它们之间的区别是:1、默认情况下,run指令会一直执行程序,直到执行结束。如果程序中手动设置有断点,则run指令会执行......