[minishell 미니쉘] 기초

Joey Hong·2020년 12월 21일
0

minishell

목록 보기
1/1

fork()로 기본 쉘 돌리기
ls, pwd 등 간단한 명령어가 가능하다

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

int main(int argc, char *argv[]) {
    char buf[128];
    pid_t pid;	//variable dealing with process ids

    while(1) {
        memset(buf, 0, sizeof(buf));
        fgets(buf, sizeof(buf) - 1, stdin);	
/*
** char *fgets(char *str, int n, FILE *stream)
** reads a line from file stream stdin
** stores it into string buf
** stops when (sizeof(buf) - 2) characters are read
** or when reading newline or reaching end-of-file
*/
        
        buf[strlen(buf) - 1] = '\0';		//so argv[0] is stored in buf	
        if(!strncmp(buf, "exit", strlen(buf))) {
            return -1;
        }
        pid = fork();					/* returns 0 to child on success */
        if(pid < 0) {					/* failed to fork() */
            perror("fork error\n");
            return -1;
        }
        else if(pid == 0) {				/*child code when pid == 0 */
            execlp(buf, buf, NULL);		/* executes buf, the stdin */
            exit(0);
        }
        else {					/* parent code when pid > 0 */
            wait(NULL);
        }
    }

    return 0;
}
profile
개발기록

0개의 댓글