多进程程序调试,通常先启动程序,然后找到进程id
启动gdb,通过attach命令连接到进程
有一程序forktest.c
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int fd[2];
char buf[128];
pid = getpid();
int i = 0;
int stat_val;
printf("parentpid = %d\n",pid);
if(pipe(fd)<0){
printf("pipe creat error");
return 0;
}
pid = fork();
if(pid<0){
printf("fork error\n");
return 0;
}
if(0==pid){
printf("this is child, pid = %d\n",getpid());
close(fd[0]);
write(fd[1],"hahahaha",8);
while(1){
if(i>10)
break;
sleep(30);
i++;
}
}else{
printf("this is parent, pid = %d,child pid=%d \n",getpid(),pid);
close(fd[1]);
int readnum = read(fd[0],buf,10);
buf[readnum]='\0';
printf("%s",buf);
waitpid(pid,&stat_val,0);
if(WIFEXITED(stat_val))
printf("child exited \n");
else if(WIFSIGNALED(stat_val))
printf("child terminate abnormally\n");
// wait(NULL);
}
return 0;
}
编译
gcc -g -o forktest forktest.c
运行
./forktest &
查看进程id
ps -ef|grep forktest
root 25555 24280 0 14:41 pts/3 00:00:00 ./forktest
root 25556 25555 0 14:41 pts/3 00:00:00 ./forktest
调试
gdb
(gdb) attach 25555
(gdb) list