进阶版多进程程序实例
主要是使用子进程去执行调用另外一个可执行程序,具体实现是调用 exec 函数簇实现一个进程对执行另外一个可执行程序的功能。
- 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[]);
- 代码
// 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;
}
- 调试
因为当前我们知道要调试子进程,所以可以在刚进入GDB页面时就开始设置对应的调试属性- GDB multiprocess
- set follow-fork-mode child
- catch exec // 捕获 exec 函数调用
- r // 执行后会直接运行到exec调用处,即子进程的执行函数处
- b main // 此时子进程的所有参数已经被替换成 multiexec 的对应的执行内容了
- c // 执行 c 而不是 s/n 的原因是,在exec调用到 main 函数中会有一些不知道什么的代码还在执行,会有好几步需要执行,索性就在 multiexec 的 main 处打上断点,然后直接执行到 main 函数处
- 调试记录
(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]);
标签:const,exec,int,程序调试,char,实例,Linux,main,multiexec
From: https://www.cnblogs.com/wanghao-boke/p/17058198.html