我需要用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 的所有子节点的列表。这在递归函数中不起作用。递归调用将覆盖数组。您必须将其设为本地变量并将其传递给必须分配值的函数:
void imprime_Pstree(int i, int ntabs)
{
int k = 0, j = 0, quantProc = 0;
int procAtual;
int processos[1000]; // <-- have a local array
// Imprime a quantidade de tabs
for(k = 0; k < ntabs; k++)
printf("\t");
// pass that array to preenche_vetor()
quantProc = preenche_vetor(i, processos );
// Imprime o nome do processo
imprimeNomeProcesso(i);
for(j = 0; j < quantProc; j++) {
imprime_Pstree(processos[j], ntabs+1);
}
}
当然,您还必须更改 preenche_vetor() 的签名,并且必须在那里进行初始化()。
编辑 正如 @Aconcagua ha 建议的那样,最好先确定 child 的数量,然后声明并填写 VLA
关于c - 不完整的 C 递归函数。我不知道如何正确实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43634267/