【问题标题】:Getting the process name and printing it out in XV6/C获取进程名称并在 XV6/C 中打印出来
【发布时间】:2021-09-11 21:04:00
【问题描述】:

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

【问题讨论】:

  • 假设你有一个pid_t(进程ID),对于通过getpid()的当前进程,在linux下,你可以在/proc/<pid>目录下查看。这就是 linux 的 ps 命令将如何做到的。 xv6/unix-v6 没有,但是,我认为它有一个ps 命令。我会查看 xv6 ps 命令的源代码以了解它的作用。尽管我 [个人] 使用了 1980 年左右的 unix-v7 [v6 已经过时],但我不记得它是如何做到的。我们只是用来捕获ps的输出并解析它。

标签: c linux xv6


【解决方案1】:

结构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 你就完成了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2023-02-18
    相关资源
    最近更新 更多