【问题标题】:System call to count number of children in a process系统调用来计算进程中的子节点数
【发布时间】:2020-04-03 02:10:30
【问题描述】:

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

proc.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;
}

sysproc.c

int
sys_getchildren(void)
{ 
    int pid;
    argint(0, &pid);
    return countChildren(pid);

}

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();
}

但是结果不是我所期望的,下面是结果:

【问题讨论】:

    标签: c process operating-system xv6


    【解决方案1】:

    我认为您的内核代码已更正,您的问题来自用户代码: 你创建了进程,但你不关心它们,所以它们变成了僵尸,无法计数。

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

    僵尸是被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();
    }
    

    编辑:你在系统调用中有一点错别字,而不是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 没有在系统调用中正确设置。查看我的更新
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    相关资源
    最近更新 更多