뭐요

xv6에서 hcat 쉘 프로그램 작성 본문

Operating System/xv6

xv6에서 hcat 쉘 프로그램 작성

욕심만 많은 사람 2023. 2. 28. 12:35

xv6에서 hcat 쉘 프로그램 작성

hcat 쉘 프로그램 작성

xv6에서 기존에 쓰여져있는 cat 명령어를 참고해서 특정 행을 출력하는 hcat 쉘프로그램을 만들어보자

우리의 목표

  • 파일의 첫 번째 행을 터미널에 출력하는 hcat.c 프로그램 작성
  • 기존에 cat.c 파일 복사
  • 출력할 행 수를 저장할 전역변수 추가
  • void cat(int fd) 함수 부분 수정
  • helloworld 과제 처럼 Makefile 수정해서 hcat.c 또한 컴파일 될 수 있도록 변경
  • xv6 실행 후 hcat 명령어 실행

 

1) cat.c의 소스코드를 복사해서 hcat.c 파일을 만든 후에 붙여넣기

 

2) char buf[1]를 size 1로 바꿈.

char buf[1];

 

3) 전역변수 cntLine 선언

int endLine;

 

4) main 함수 수정

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

  if(argc <= 2){    // 1 -> 2로 수정 (인자 전달 형태 변경)
    hcat(0);
    exit();
  }

  endLine = atoi(argv[1]);   // 실행할 라인 인자에서 전달받음

  for(i = 2; i < argc; i++){
    if((fd = open(argv[i], 0)) < 0){
      printf(1, "cat: cannot open %s\\n", argv[i]);
      exit();
    }
    hcat(fd);
    close(fd);
  }
  exit();
}

 

5) hcat 함수 수정

void hcat(int fd)
{
  int n;
  int cntLine = 0;    // 현재 라인

      while((n = read(fd, buf, sizeof(buf))) > 0) {
        if (write(1, buf, n) != n) {
      printf(1, "cat: write error\\n");
      exit();
    }
        // 라인 검사 (개행이 일어나면 cntLine+1)
    if(buf[0] == '\\n'){
      cntLine++;
      if(cntLine == endLine){
        break;
      }
    }
  }
  if(n < 0){
    printf(1, "cat: read error\\n");
    exit();
  }
}

 

6) 실행결과

$ hcat 5 README

NOTE: we have stopped maintaining the x86 version of xv6, and switched
our efforts to the RISC-V version
(<https://github.com/mit-pdos/xv6-riscv.git>)

xv6 is a re-implementation of Dennis Ritchie's and Ken Thompson's Unix

 

7) 실행사진

image