Shell

youngwiki
Pinkgo (토론 | 기여)님의 2025년 3월 15일 (토) 14:43 판

상위 문서: Signals and Nonlocal jumps

개요

Shell이란 사용자 명령을 실행하는 애플리케이션 프로그램이다. 다음은 shell의 대표적인 예시이다.

  • sh : 오리지널 Unix 쉘 (Stephen Bourne, AT&T Bell Labs, 1977)
  • csh/tcsh : BSD Unix C 쉘
  • bash : Bourne-Again Shell (리눅스 기본 쉘)

Shell은 아용자의 명령어를 입력받고, 이를 실행시키는 식으로 작동한다.

예시

int main() {
    char cmdline[MAXLINE]; /* command line */
    while (1) {
        /* read */
        printf("> ");
        Fgets(cmdline, MAXLINE, stdin);
        if (feof(stdin))
            exit(0);
        
        /* evaluate */
        eval(cmdline);
    }
}
void eval(char *cmdline) {
    char *argv[MAXARGS]; /* Argument list execve() */
    char buf[MAXLINE]; /* Holds modified command line */
    int bg; /* Should the job run in bg or fg? */
    pid_t pid; /* Process id */
    
    strcpy(buf, cmdline);
    bg = parseline(buf, argv);
    if (argv[0] == NULL)
        return; /* Ignore empty lines */

    if (!builtin_command(argv)) {
        if ((pid = fork()) == 0) { /* Child runs user job */
            if (execve(argv[0], argv, environ) < 0) {
                printf("%s: Command not found.\n", argv[0]);
                exit(0);
            }
        }
        /* Parent waits for foreground job to terminate */
        if (!bg) {
            int status;
            if (waitpid(pid, &status, 0) < 0)
                unix_error("waitfg: waitpid error");
        } else {
            printf("%d %s\n", pid, cmdline);  // 개행 추가
        }
    }
    return;
}

각주