aboutsummaryrefslogtreecommitdiffstats
path: root/ramfs/src/ptree.c
blob: 2773140cc2e87872826eb2e90bf5ed909eece283 (plain) (blame)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syscall.h>

#define __NR_ptree 313

struct prinfo {
	long state;
	pid_t pid;
	pid_t parent_pid;
	pid_t first_child_pid;
	pid_t next_sibling_pid;
	long uid;
	char comm[64];
};

static inline int ptree(struct prinfo *processes, unsigned int *count)
{
	return syscall(__NR_ptree, processes, count);
}

static pid_t find_parent(struct prinfo *processes, unsigned int count, pid_t pid)
{
	int i;
	for (i = 0; i < count; ++i) {
		if (processes[i].pid == pid)
			return processes[i].parent_pid;
	}
	return 0;
}

static int hilariously_inefficient_method_of_finding_indentation_level(struct prinfo *processes, unsigned int count, pid_t pid)
{
	int indentation = 0;
	while((pid = find_parent(processes, count, pid)))
		++indentation;
	return indentation;

	/* Bonus points if you can find a reasonable _looking_
	 * algorithm that is even more inefficient. */
}

int main(int argc, char *argv[])
{
	struct prinfo *processes;
	unsigned int count, indentation, i, j;
	pid_t last_ppid;

	indentation = 0;

	count = 32768;
	processes = malloc(sizeof(struct prinfo) * count);
	if (!processes) {
		perror("processes");
		return EXIT_FAILURE;
	}

	memset(processes, 0, sizeof(struct prinfo) * count);

	if (ptree(processes, &count)) {
		perror("ptree");
		return EXIT_FAILURE;
	}

	for (i = 0; i < count; ++i) {
		indentation = hilariously_inefficient_method_of_finding_indentation_level(processes, count, processes[i].pid);
		for (j = 0; j < indentation; ++j)
			putchar('\t');
		printf("%s,%d,%ld,%d,%d,%d,%ld\n", processes[i].comm, processes[i].pid,
			processes[i].state, processes[i].parent_pid, processes[i].first_child_pid,
			processes[i].next_sibling_pid, processes[i].uid);
	}

	printf("%d processes\n", count);

	return EXIT_SUCCESS;
}