Linux

[Linux, C] 나만의 간단한 Linux 쉘 만들기 (fork, exec사용)

반나무 2020. 10. 29. 10:55
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

#define MAX 255

void *prompt(char cBuf[]) {
        char hBuf[MAX], uBuf[MAX], dBuf[MAX];
        char *now;
        void *ret;

        //now[strlen(now)-1] = 0;

        gethostname(hBuf,MAX);
        getlogin_r(uBuf,MAX);
        getcwd(dBuf,MAX);

        printf("%s@%s(%s)#", hBuf, uBuf, dBuf);

        ret = fgets(cBuf, MAX, stdin);

        if(cBuf[strlen(cBuf)-1] == '\n')
                cBuf[strlen(cBuf)-1] = 0;

        return ret;
}

int main(){
        char cBuf[MAX];
        char *arg;
        pid_t pid;
        int status;

        while(prompt(cBuf)) {

                if((pid = fork()) < 0){
                        perror("fork error");
                }
                
                // strcmp : 문자열 같은지 체크, 같으면 0을 반환
                if(strcmp(cBuf, "exit") == 0){
                        exit(0);
                }
				
                
                else if(pid == 0){ // chilren case
                		// strkot : 문자열 자르기
                        strtok(cBuf, " ");
                        arg = strtok(NULL, " ");

                        if(arg == NULL){
                                execlp(cBuf, cBuf, (char*) 0);

                        } else {
                                if(strcmp(cBuf, "cd") == 0){
                                        chdir(arg);
                                        _exit(0);
                                } else {
                                        execlp(cBuf, cBuf, arg, (char*) 0);
                                }
                        }
                        perror("couldn't execute");
                }

                waitpid(pid, &status, 0);
        }

        exit(0);
}

참고 

전체적인 코드 

devsophia.tistory.com/entry/%EB%82%98%EB%A7%8C%EC%9D%98-%EA%B0%84%EB%8B%A8%ED%95%9C-LINUX-shell-%EB%A7%8C%EB%93%A4%EA%B8%B0

 

execlp

forum.falinux.com/zbxe/index.php?document_srl=408557&mid=C_LIB

 

반응형