Linux 多进程程序调试实例(二)-exec函数的使用

进阶版多进程程序实例

主要是使用子进程去执行调用另外一个可执行程序,具体实现是调用 exec 函数簇实现一个进程对执行另外一个可执行程序的功能。

  1. exec 函数簇定义
#include <unistd.h>

extern char **environ;

int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg,..., char * const envp[]);
int execv(const char *path, char *constargv[]);
int execvp(const char *file, char *constargv[]);
int execvpe(const char *file, char *const argv[],char *const envp[]);
  1. 代码
// multiprocess.cpp
#include<iostream>
#include<unistd.h>
#include<cstdio>
int main()
{
    pid_t pid = fork();
    if( 0 == pid ) {
        std::cout << "hi, I'am a child process and the process id is " << getpid() << std::endl;
        execl("./multiexec","multiexec","arg1","arg2",NULL);
    }
    else if(pid > 0){
        std::cout << "hi, I'am a parent process and the process id is " << getpid() << std::endl;
    }
    else{
        perror("fork");
    }
    return 0;
}
// multiexec.cpp
#include<iostream>
#include<cstdio>

int main(int argc, char* argv[]){
    std::cout << __FILE__ << " " << __func__ << " " << __LINE__ << std::endl;

    if(argc > 1) {
        for(int i = 0; i < argc; ++i){
            printf("argv[%d]: %s\n", i, argv[i]);
        }
    }
    return 0;
}
  1. 调试
    因为当前我们知道要调试子进程,所以可以在刚进入GDB页面时就开始设置对应的调试属性
    1. GDB multiprocess
    2. set follow-fork-mode child
    3. catch exec // 捕获 exec 函数调用
    4. r // 执行后会直接运行到exec调用处,即子进程的执行函数处
    5. b main // 此时子进程的所有参数已经被替换成 multiexec 的对应的执行内容了
    6. c // 执行 c 而不是 s/n 的原因是,在exec调用到 main 函数中会有一些不知道什么的代码还在执行,会有好几步需要执行,索性就在 multiexec 的 main 处打上断点,然后直接执行到 main 函数处
  2. 调试记录
(gdb) set follow-fork-mode child
(gdb) catch exec 
Catchpoint 1 (exec)
(gdb) r
Starting program: /home/user/Desktop/code/ProgramDebug/multiprocess/multiprocess 
hi, I'am a parent process and the process id is 7621
[New process 7625]
hi, I'am a child process and the process id is 7625
process 7625 is executing new program: /home/user/Desktop/code/ProgramDebug/multiprocess/multiexec
[Switching to process 7625]

Thread 2.1 "multiexec" hit Catchpoint 1 (exec'd /home/user/Desktop/code/ProgramDebug/multiprocess/multiexec), 0x00007ffff7dd7c30 in _start () from /lib64/ld-linux-x86-64.so.2
(gdb) b main
Breakpoint 2 at 0x4008e5: file multiexec.cpp, line 6.
(gdb) c
Continuing.

Thread 2.1 "multiexec" hit Breakpoint 2, main (argc=2, argv=0x7fffffffee28) at multiexec.cpp:6
warning: Source file is more recent than executable.
6
(gdb) n
multiexec.cpp main 6
8               for(int i = 0; i < argc; ++i){
(gdb) 
9                   printf("argv[%d]: %s\n", i, argv[i]);
posted @   王清河  阅读(236)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示