시스템 프로그래밍 리눅스 쉘 구현 코드 질문입니다.
-
코드를 받아서 읽고 해석하려고 하는데 좀 어렵네요..ㅠㅠ
일단 필수 구현내용은
(1) 명령줄에서 파이프는 한번만 허용된다.
(2) fork, pipe 시스템호출을 사용한다.cd명령어도 작동을 안하고 코드가 무슨 내용을 의미하는지 해석이 어렵네요..ㅠㅠ
<코드>
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> static char *args[512]; pid_t pid; int command_pipe[2]; #define READ 0 #define WRITE 1 static int command(int input, int first, int last) { int pipettes[2]; pipe(pipettes); pid = fork(); if (pid == 0) { if (first == 1 && last == 0 && input == 0) { dup2(pipettes[WRITE], STDOUT_FILENO); } else if (first == 0 && last == 0 && input != 0) { dup2(input, STDIN_FILENO); dup2(pipettes[WRITE], STDOUT_FILENO); } else { dup2(input, STDIN_FILENO); } if (execvp(args[0], args) == -1) _exit(EXIT_FAILURE); } if (input != 0) close(input); close(pipettes[WRITE]); if (last == 1) close(pipettes[READ]); return pipettes[READ]; } static void cleanup(int n) { int i; for (i = 0; i < n; ++i) wait(NULL); } static int run(char *cmd, int input, int first, int last); static char line[1024]; static int n = 0; int main() { printf("SIMPLE SHELL: Type 'exit' or send EOF to exit.\n"); while (1) { printf("$> "); fflush(NULL); if (!fgets(line, 1024, stdin)) return 0; int input = 0; int first = 1; char *cmd = line; char *next = strchr(cmd, '|'); while (next != NULL) { *next = '\0'; input = run(cmd, input, first, 0); cmd = next + 1; next = strchr(cmd, '|'); first = 0; } input = run(cmd, input, first, 1); cleanup(n); n = 0; } return 0; } static void split(char *cmd); static int run(char *cmd, int input, int first, int last) { split(cmd); if (args[0] != NULL) { if (strcmp(args[0], "exit") == 0) exit(0); n += 1; return command(input, first, last); } return 0; } static char *skipwhite(char *s) { while (isspace(*s)) ++s; return s; } static void split(char *cmd) { cmd = skipwhite(cmd); char *next = strchr(cmd, ' '); int i = 0; while (next != NULL) { next[0] = '\0'; args[i] = cmd; ++i; cmd = skipwhite(next + 1); next = strchr(cmd, ' '); } if (cmd[0] != '\0') { args[i] = cmd; next = strchr(cmd, '\n'); next[0] = '\0'; ++i; } args[i] = NULL; }
-
해결했습니다. 감사합니다 ~