user/init.c

54 lines
1// init: The initial user-level program23#include "kernel/types.h"4#include "kernel/stat.h"5#include "kernel/spinlock.h"6#include "kernel/sleeplock.h"7#include "kernel/fs.h"8#include "kernel/file.h"9#include "user/user.h"10#include "kernel/fcntl.h"1112char *argv[] = { "sh", 0 };1314int15main(void)16{17  int pid, wpid;1819  if(open("console", O_RDWR) < 0){20    mknod("console", CONSOLE, 0);21    open("console", O_RDWR);22  }23  dup(0);  // stdout24  dup(0);  // stderr2526  for(;;){27    printf("init: starting sh\n");28    pid = fork();29    if(pid < 0){30      printf("init: fork failed\n");31      exit(1);32    }33    if(pid == 0){34      exec("sh", argv);35      printf("init: exec sh failed\n");36      exit(1);37    }3839    for(;;){40      // this call to wait() returns if the shell exits,41      // or if a parentless process exits.42      wpid = wait((int *) 0);43      if(wpid == pid){44        // the shell exited; restart it.45        break;46      } else if(wpid < 0){47        printf("init: wait returned an error\n");48        exit(1);49      } else {50        // it was a parentless process; do nothing.51      }52    }53  }54}55