首页 > 解决方案 > 获取进程名称并在 XV6/C 中打印出来

问题描述

我是 XV6 的新手,并试图弄清楚如何打印出进程名称。我最初的想法是获取进程 ID 并以某种方式从中获取进程名称。任何想法都会很棒。谢谢!

标签: clinuxxv6

解决方案


该结构struct proc包含name作为进程名称的字段。

因此,您可以使用一些代码打印它。

就像是:

/*The system call*/
/* in sysproc.c*/
int
sys_printname(void){
    int pid;

    /* get syscall argument */
    if (argint(0, &pid) < 0)
        return -1;

    return printname(pid);
}
/* in proc.c */
int
printname(int pid){
    int found = 0;
    struct proc *p;
    char name[16];

    /* search for the wanted process */
    acquire(&ptable.lock);
    for (p = ptable.proc; p < &ptable.proc[NPROC]; p++) {
        if (p->pid == pid) {
            /* found */
            found = 1;
            /* copy string to our buffer. */
            safestrcpy(name, p->name, sizeof name);
            break;
        }
    }

    release(&ptable.lock);

    if (!found)
        return -2;

    cprintf("%d: %s\n", pid, name);
    return 0;
}

不要忘记更新文件:(查看其他系统调用是如何实现的)

  • syscall.c
  • syscall.h
  • usys.S
  • user.h

然后你可以在程序中使用你的系统调用:

pname.c(kill.c 的快速副本)

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

int
main(int argc, char **argv)
{
  int i;

  if(argc < 2){
    printf(2, "usage: pname pid...\n");
    exit();
  }
  for(i=1; i<argc; i++)
    sys_printname(atoi(argv[i]));
  exit();
}

将其添加到Makefile(灵感来自其他用户程序,例如kill

make你完成了


推荐阅读