请用C++实现遍历当前系统中的所有进程,并能用树状结构显示进程之间的父子关系。
时间: 2023-04-03 12:04:55 浏览: 108
好的,我可以回答这个问题。以下是用 C 实现遍历当前系统中的所有进程,并用树状结构显示进程之间的父子关系的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <ctype.h>
#define MAX_PATH 1024
#define MAX_NAME 256
typedef struct proc_node {
int pid;
int ppid;
char name[MAX_NAME];
struct proc_node *child;
struct proc_node *sibling;
} proc_node;
proc_node *root = NULL;
void add_node(proc_node *parent, proc_node *child) {
if (parent->child == NULL) {
parent->child = child;
} else {
proc_node *sibling = parent->child;
while (sibling->sibling != NULL) {
sibling = sibling->sibling;
}
sibling->sibling = child;
}
}
void free_tree(proc_node *node) {
if (node == NULL) {
return;
}
free_tree(node->child);
free_tree(node->sibling);
free(node);
}
void print_tree(proc_node *node, int depth) {
if (node == NULL) {
return;
}
for (int i = 0; i < depth; i++) {
printf(" ");
}
printf("%d %s\n", node->pid, node->name);
print_tree(node->child, depth + 1);
print_tree(node->sibling, depth);
}
int is_number(const char *str) {
for (int i = 0; str[i] != '\0'; i++) {
if (!isdigit(str[i])) {
return 0;
}
}
return 1;
}
void read_proc_stat(const char *path, int *pid, int *ppid, char *name) {
FILE *fp = fopen(path, "r");
if (fp == NULL) {
return;
}
fscanf(fp, "%d %s %*c %d", pid, name, ppid);
fclose(fp);
}
void traverse_proc(const char *path, proc_node *parent) {
DIR *dir = opendir(path);
if (dir == NULL) {
return;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (is_number(entry->d_name)) {
char stat_path[MAX_PATH];
snprintf(stat_path, sizeof(stat_path), "%s/%s/stat", path, entry->d_name);
int pid, ppid;
char name[MAX_NAME];
read_proc_stat(stat_path, &pid, &ppid, name);
proc_node *node = (proc_node *)malloc(sizeof(proc_node));
node->pid = pid;
node->ppid = ppid;
strncpy(node->name, name + 1, MAX_NAME - 1);
node->child = NULL;
node->sibling = NULL;
add_node(parent, node);
char subdir[MAX_PATH];
snprintf(subdir, sizeof(subdir), "%s/%s", path, entry->d_name);
traverse_proc(subdir, node);
}
}
closedir(dir);
}
int main() {
root = (proc_node *)malloc(sizeof(proc_node));
root->pid = 0;
root->ppid = 0;
strncpy(root->name, "root", MAX_NAME - 1);
root->child = NULL;
root->sibling = NULL;
traverse_proc("/proc", root);
print_tree(root, 0);
free_tree(root);
return 0;
}
阅读全文