我想创建一个进程树,就像图片上的一样。这个
Z
进程应该在秒后显示整个树作为程序参数,我需要处理树的正确销毁。另外,我不能使用
sleep()
命令。程序输出应如下所示:
Iâm the process arb: my pid is 751
Iâm the process A: my pid is 752. My father is 751
Iâm the process B: my pid is 753. My father is 752, grandfather 751
Iâm the process X: my pid is 754. My father is 753, grandfather 752, great-grandfather is 751
Iâm the process Y: my pid is 755. My father is 753, grandfather 752, great-grandfather is 751
Iâm the process Z: my pid is 756. My father is 753, grandfather 752, great-grandfather is 751
//wait some seconds and display process tree
I am Z (755) and I die
I am Y (755) and I die
I am X (754) and I die
I am B (753) and I die
I am A (752) and I die
I am arb (751) and I die
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
int arb;
void z_function() {
printf("pstree\n");
execl("/bin/pstree", "pstree", "-p", arb, (char*)0);
printf("I am Z (%d) and I die\n", getpid());
kill(getpid(), SIGKILL);
}
int main(int argc, char **argv) {
signal(SIGALRM, z_function);
int arg = atoi(argv[1]);
printf("arg: %d\n", arg);
arb = getpid();
printf("I'm the process arb: my pid is %d\n", getpid());
//A
if (fork() == 0) {
int a = getpid();
printf("I'm the process A: my pid is %d. My father is %d\n", getpid(), getppid());
//B
if (fork() == 0) {
int b = getpid();
printf("I'm the process B: my pid is %d. My father is %d, grandfather %d\n", getpid(), getppid(), arb);
int children[3];
for (int i = 0; i < 3; i++) {
if (fork() == 0) {
children[i] = getpid();
switch(i) {
case 0:
printf("I'm the process X: my pid is %d. My father is %d, grandfather %d, great-grandfather is %d\n", getpid(), getppid(), a, arb);
wait(NULL);
break;
case 1:
printf("I'm the process Y: my pid is %d. My father is %d, grandfather %d, great-grandfather is %d\n", getpid(), getppid(), a, arb);
wait(NULL);
break;
case 2:
printf("I'm the process Z: my pid is %d. My father is %d, grandfather %d, great-grandfather is %d\n", getpid(), getppid(), a, arb);
alarm(arg);
pause();
//exit(0);
break;
}
}
else {
wait(NULL);
}
}
wait(NULL);
kill(children[1], SIGKILL);
printf("I am Y (%d) and I die\n", children[1]);
kill(children[0], SIGKILL);
printf("I am X (%d) and I die\n", children[0]);
printf("I am B (%d) and I die\n", getpid());
exit(0);
}
wait(NULL);
printf("I am A (%d) and I die\n", getpid());
exit(0);
}
else {
wait(NULL);
printf("I am arb (%d) and I die\n", getpid());
exit(0);
}
while (wait(NULL) > 0)
exit(0);
return 0;
}