提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
一、创建1层10个子进程
1.题目
2.代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char* argv[])
{
pid_t pid;
char cmd[100];
//---------begin---------------
for(int i=0;i<10;i++)
{
pid=fork();
if(pid==0)
{
exit(1);
}
}
//-----------End--------------
sprintf(cmd, "pstree %d > temp", getpid());
system(cmd);
}
3.思路
循环使用fork(),在当前进程为子进程的时候使用exit()终止进程。
exit(0):正常运行程序并退出程序,调用时程序运行正常结束;
exit(1):非正常运行导致退出程序,调用时程序运行非正常结束;
二、创建10层1个子进程
1.题目
2.代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char* argv[])
{
pid_t pid,top_pid;
int i = 1;
char cmd[100];
top_pid=getpid();
//*************Begin*******************
for(i;i<10;i++)
{
pid=fork();
if(pid>0)
{
break;
}
if(i==9)
{
sprintf(cmd, "pstree %d > temp", top_pid);
system(cmd);
}
}
sleep(1);
//*************End*********************
}
3.思路:
同样循环使用fork(),与上题不同。在当前进程为父进程时,不能使用exit(0)来终止进程,反而需要使用sleep()保证在获取树结构的时候,进程未退出。
三、创建3层完全二叉树式进程
1.题目
2.代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <math.h>
void CheckProcessTree(pid_t top_pid);
void GenerateChildProcess(); //补充完整
int main(int argc, char* argv[])
{
pid_t top_pid;
int level = 3;
char cmd[100];
top_pid = getpid();
GenerateChildProcess(level,top_pid);//补充完整
//CheckProcessTree(top_pid);
}
void CheckProcessTree(pid_t top_pid)
{
char cmd[100];
sprintf(cmd, "pstree %d >temp", top_pid);
system(cmd);
}
void GenerateChildProcess(int level,pid_t top_pid)//参数自己定义
{
//在该函数内实现生成进程树结构,注意在每个子进程中停留10s
//整个进程树建成后,调用CheckProcessTree()
pid_t pid1=0;
pid_t pid2=0;
int i=0;
for(i;i<level;i++)
{
pid1=fork();
if(pid1)
{
pid2=fork();
if(pid2)
{
//exit(1);
break;
}
}
//CheckProcessTree(top_pid);
}
waitpid(pid1,NULL,0);
waitpid(pid2,NULL,0);
sleep(1);
}
四、总结
1.gdb调试多进程
a.使用gdb调试多进程程序,使用gdb进行调试时,需要在编译的时候加上-g。对于多进程程序,默认调试的是父进程,
2.gdb一些常用指令
-r :运行
-n:下一句
-q:退出
-b:设置断点,其后可加上某一行的行数或函数名