C 对进程中的子进程数进行计数的系统调用

C 对进程中的子进程数进行计数的系统调用,c,process,operating-system,xv6,C,Process,Operating System,Xv6,我已经完成了创建系统调用的所有步骤,然后创建了一个用户程序并运行它: 程序c int countChildren (int pid) { struct proc *p; int count = 0; acquire(&ptable.lock); for(p = ptable.proc; p < &ptable.proc[NPROC]; p++) if(p->parent->pid == pid) count++;

我已经完成了创建系统调用的所有步骤,然后创建了一个用户程序并运行它:

程序c

int countChildren (int pid) {

    struct proc *p;
    int count = 0;

    acquire(&ptable.lock);

    for(p = ptable.proc; p < &ptable.proc[NPROC]; p++)
      if(p->parent->pid == pid) count++;

    release(&ptable.lock);

    return count;
}
userProgram.c

...
#include "types.h"
#include "user.h"

int main (void) {

    int n1 = fork(); 

    int n2 = fork();

    int n3 = fork();

    int n4 = fork(); 

    if (n1 > 0 && n2 > 0 && n3 > 0 && n4 > 0) { 
        printf(1,"parent\n"); 
        printf(1," getchildren = %d \n", getchildren()); 
    } 
    exit();
}
但结果并非我所预期的,以下是结果:


我认为您的内核代码已经纠正,您的问题来自用户代码: 您创建了进程,但没有处理它们,因此它们变成了僵尸,无法计数

当一个进程退出并且没有被其父进程等待时,它将变成一个僵尸:

僵尸是指init进程采用的进程(请参见文件
proc.c
中的
exit
定义),不能计入子进程

要更正测试代码,请使进程休眠一段时间并等待其子进程:

#include "types.h"
#include "user.h"

int main (void) {

    int n1 = fork(); 
    int n2 = fork();
    int n3 = fork();
    int n4 = fork(); 

    if (n1 > 0 && n2 > 0 && n3 > 0 && n4 > 0) { 
        printf(1,"parent\n"); 
        printf(1," getchildren = %d \n", getchildren()); 
    } 

    /* wait for all child to terminate */
    while(wait() != -1) { }

    /* give time to parent to reach wait clause */
    sleep(1);

    exit();
}

编辑:您在syscall中有一点输入错误,而不是
getint
,您应该从
myproc
获取
pid

int
sys_getchildren(void)
{ 
    int pid;
    pid = myproc()->pid;
    return countChildren(pid);
}
或更短:

int
sys_getchildren(void)
{ 
    return countChildren(myproc()->pid);
}

即使当我使用上面的代码时,它也会说
getchildren=1
而父进程应该有4个直接子进程,我错了吗?@mahdigh:事实上,
pid
没有在syscall中正确设置。查看我的更新
int
sys_getchildren(void)
{ 
    return countChildren(myproc()->pid);
}