【发布时间】:2017-04-26 12:29:44
【问题描述】:
我需要在C中实现一个可以模拟pstree的递归函数,也就是把下面的数字想象成一个进程:
1 (father)
2 (child of 1)
3 (child of 1)
4 (son of 3)
5 (child of 4)
6 (child of 3)
等等……
void imprime_Pstree(int i, int ntabs)
{
int k = 0, j = 0, quantProc = 0;
int procAtual;
// Prints the number of tabs
for(k = 0; k < ntabs; k++)
printf("\t");
quantProc = preenche_vetor(i);
// Prints the process name
imprimeNomeProcesso(i);
for(j = 0; j < quantProc; j++) {
imprime_Pstree(processos[j], ntabs+1);
}
}
但它只打印父级(称为递归函数)和相同的子级,没有其他子级。 我知道在前一个孩子的父级中丢失了对递归函数的另一个调用,但是如何呢?
完整代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
int processos[1000];
void limpa_vetor() {
int i;
for(i = 0; i < 1000; i++)
processos[i] = 0;
}
int preenche_vetor(int proc) {
char path[50];
char string[100];
int i, j = 0, cont = 0;
char temp;
FILE *arq;
limpa_vetor();
sprintf(path, "/proc/%d/task/%d/children", proc, proc);
arq = fopen(path, "r");
if (arq != NULL)
{
limpa_vetor();
fscanf(arq, "%s", string);
while(strcmp(string, "") != 0)
{
if(feof(arq)) break;
processos[j] = atoi(string);
cont++;
fscanf(arq, "%c", &temp);
fscanf(arq, "%s", string);
j++;
}
}
return cont;
}
void imprimeNomeProcesso(int proc) {
char path[50];
char string[100];
int i, j = 0;
char temp;
FILE *arq;
sprintf(path, "/proc/%d/stat", proc);
arq = fopen(path, "r");
if (arq != NULL)
{
fscanf(arq, "%s", string);
while(strcmp(string, "") != 0)
{
if(feof(arq)) break;
if(j == 1)
{
printf("%s ", string);
break;
}
fscanf(arq, "%c", &temp);
fscanf(arq, "%s", string);
j++;
}
printf("\n");
}
}
void imprime_Pstree(int i, int ntabs)
{
int k = 0, j = 0, quantProc = 0;
int procAtual;
// Imprime a quantidade de tabs
for(k = 0; k < ntabs; k++)
printf("\t");
quantProc = preenche_vetor(i);
// Imprime o nome do processo
imprimeNomeProcesso(i);
for(j = 0; j < quantProc; j++) {
imprime_Pstree(processos[j], ntabs+1);
}
}
int main()
{
imprime_Pstree(1, 0);
return 0;
}
【问题讨论】:
-
看来
processos是一个全局变量,其中包含i的所有子项的列表。这在递归函数中不起作用。递归调用将覆盖数组。您必须将其设为本地 var 并将其传递给必须分配值的函数