Linux Shell 구현
fork함수와 execl함수를 이용하여 Shell 구현.
1. 사용자 명령을 읽기 위한 프롬프트 출력
2. 키보드로 명령을 받는다.
3. fork 함수로 자식 프로세스 생성. 부모 프로세스는 자식 프로세스가 종료되는 걸 기다림.
4. execl 함수로 외부 프로그램(프롬프트 실행)을 실행한다
5. 외부 프로그램 종료(자식 프로세스도 종료)
6. 부모 프로세스는 자식 프로세스가 종료된 걸 확인하고, 다시 프롬프트를 띄움.
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#define MAX_LINE 256
#define PROMPT "# "
#define chop(str) str[strlen(str) -1] = 0x00;
int main(int argc, char **argv)
{
char buf[MAX_LINE];
int proc_status;
pid_t pid;
printf("My Shell VEr 1.0\n");
while(1)
{
memset(buf, 0x00, MAX_LINE);
fgets(buf, MAX_LINE-1, stdin);
if(strncmp(buf, "quit\n", 5) == 0)
{
break;
}
chop(buf);
pid = fork(); // process copy
if(pid==0)
{
if(execl(buf, buf, NULL) == -1)
{
printf("Execl failure\n");
exit(0);
}
}
if(pid>0)
{
printf("Cld wait\n");
wait(&proc_status);
printf("Cild exit\n");
}
}
return 0;
}