我需要实现在C递归函数,可以模拟一个pstree,就是想象中的数字下面的过程:不完整的C递归函数。我不知道如何实现正确
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'的所有子元素的列表。这在递归函数中不起作用。递归调用将覆盖数组。您必须将其设置为本地变量并将其传递给需要分配值的函数 –