-
Notifications
You must be signed in to change notification settings - Fork 5
/
forkexectree.cc
63 lines (52 loc) · 1.03 KB
/
forkexectree.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "types.h"
#include "user.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NCHILD 2
#define NDEPTH 5
void
forktree(int depth)
{
if (depth == 0) {
printf("%d: forkexectree\n", getpid());
}
if (depth >= NDEPTH)
exit(0);
for (int i = 0; i < NCHILD; i++) {
int pid = fork();
if (pid < 0) {
die("fork error");
}
if (pid == 0) {
depth++;
char depthbuf[16];
snprintf(depthbuf, sizeof(depthbuf), "%d", depth);
const char *av[] = { "forkexectree", depthbuf, 0 };
int r = execv("forkexectree", const_cast<char * const *>(av));
die("forkexectree: exec failed %d", r);
}
}
for (int i = 0; i < NCHILD; i++) {
if (wait(NULL) < 0) {
die("wait stopped early");
}
}
if (wait(NULL) != -1) {
die("wait got too many");
}
if (depth > 0)
exit(0);
printf("%d: forkexectree OK\n", getpid());
// halt();
}
int
main(int ac, char **av)
{
if (ac == 1) {
forktree(0);
} else {
forktree(atoi(av[1]));
}
return 0;
}