Search code examples
ckernelxv6

Implementing a syscall in xv6


I am trying to implement a syscall, called getprocs() which returns the number of actual processes. I have already implemented all the necessities to add a new syscall. What this syscall does is get the processes in the table and copies them to an array of structs. The struct is called uproc, where its members are int pid, int ppid, and char name. I then have created a program in a.c file that tries to print the processes in tree format but I am having trouble just printing the process name.I do not know where to go from here. Below I have attached my code where i define getprocs(), the struct uproc, and my program that tries to print the processes. I also included the error it throws at me.

getprocs() definition in proc.c:

int 
sys_getprocs(void)
{
int max;
struct uproc *p;
int i = 0;
argint(0, &max);
argptr(1, (char **)&p, max*sizeof(struct uproc));
struct proc *ptr = ptable.proc;
for(; ptr < &ptable.proc[NPROC]; ptr++) {
  if(!(ptr->state == UNUSED)) {
    continue;
  }
  p[i].pid = ptr->pid;
  p[i].ppid = ptr->parent->pid;
  strncpy(p[i].name, ptr->name, 16);
  i++;
}
return i;
}

struct uproc in uproc.h:

struct uproc {
    int pid;
    int ppid;
    char name[16];
 };

program that tries to print processes in pstree.c:

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

int main() {
  printf(20, "Made it into main\n");
  int maxElements = 64;
  struct uproc *processes = malloc(maxElements*sizeof(struct uproc));
  int N = getprocs(maxElements, &processes);
  int i = 0;

  printf(10, "Starting\n");
  for(; i < N; i++) {
    printf(16, processes[i].name);     
  }

  return 0;
 }

Nothing is ever printed to the screen and I get the following error after trying to run pstree:

pid 3 pstree: trap 14 err 4 on cpu 1 eip 0x6da addr 0x42444cb--kill proc


Solution

    1. For sys_getprocs, change this...

      if(!(ptr->state == UNUSED)) {
          continue;
      }
      

      to...

      if((ptr->state == UNUSED)) {
          continue;
      }
      

      Because you want to get all the running processes.

    2. In main, change...

      int N = getprocs(maxElements, &processes);

      to...

      int N = getprocs(maxElements, processes);

      since processes already defined as a pointer

    Changing these two parts of your code should make the program work.