Skip to content

Commit b6c5abd

Browse files
committed
Add thread_create
1 parent 72bb911 commit b6c5abd

File tree

2 files changed

+46
-6
lines changed

2 files changed

+46
-6
lines changed

frk.c

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,75 @@
1+
#define _DEFAULT_SOURCE
2+
3+
#include <stdatomic.h>
14
#include <stdbool.h>
25
#include <stdlib.h>
36
#include <stdio.h>
47

58
#include <sys/types.h>
69
#include <sys/wait.h>
10+
#include <sys/mman.h>
11+
#include <unistd.h>
712

813
#include "frk.h"
914

15+
struct shared_data {
16+
atomic_int total_threads;
17+
atomic_int total_processes;
18+
};
19+
1020
static bool initialized = false;
1121
static int depth = 0;
22+
static int thread_nr = 0;
23+
static struct shared_data *shared_data = NULL;
1224

1325
static void close_graph(void) {
1426
while(wait(NULL) != -1);
27+
if(thread_nr > 0) {
28+
printf(" %d [xlabel=\"T: %d\"];\n", getpid(), thread_nr);
29+
}
1530
if(depth == 0) {
31+
printf(" label=\"Total threads: %d\\nTotal processes: %d\";\n", shared_data->total_threads, shared_data->total_processes);
1632
printf("}\n");
1733
}
34+
if(munmap(shared_data, sizeof(struct shared_data)) == -1) {
35+
perror("munmap");
36+
}
1837
}
1938

20-
pid_t frk(void) {
21-
if(!initialized) {
22-
printf("digraph process_tree {\n");
23-
printf(" %d [label=\"root\"];\n", getpid());
24-
atexit(close_graph);
25-
initialized = true;
39+
static void initialize(void) {
40+
if(initialized) {
41+
return;
42+
}
43+
shared_data = mmap(NULL, sizeof(struct shared_data), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
44+
if(shared_data == MAP_FAILED) {
45+
perror("mmap");
46+
exit(1);
2647
}
48+
shared_data->total_threads = 0;
49+
shared_data->total_processes = 1;
50+
printf("digraph process_tree {\n");
51+
printf(" %d [label=\"root\"];\n", getpid());
52+
atexit(close_graph);
53+
initialized = true;
54+
}
55+
56+
pid_t frk(void) {
57+
initialize();
2758
fflush(stdout);
2859
pid_t child = fork();
2960
if(child != 0) {
3061
printf(" %d -> %d;\n", getpid(), child);
3162
printf(" %d [label=\"lvl %d\"];\n", child, depth + 1);
3263
} else {
3364
depth++;
65+
thread_nr = 0;
66+
shared_data->total_processes++;
3467
}
3568
return child;
3669
}
70+
71+
void thread_create(void) {
72+
initialize();
73+
thread_nr++;
74+
shared_data->total_threads++;
75+
}

frk.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
#include <sys/types.h>
22

33
pid_t frk(void);
4+
void thread_create(void);

0 commit comments

Comments
 (0)