To implement a shell interpreter of its own, the principle is relatively simple, first get the user's input, through the fork () function to get two processes (parent-child process), the child process through the EXECVP () function continues, at this time the parent process has been waiting for the end of the child process, The shell explanation was executed at the end of the stay.
1 /*============================================2 > Copyright (C) All rights reserved.3 > Filename:my_shell.c4 > Author:donald5 > Date:2014/08/21/16:08:036 > Details:7 ==============================================*/8#include <unistd.h>9#include <stdio.h>Ten#include <stdlib.h> One#include <string.h> A#include <sys/wait.h> -#include <sys/types.h> - #defineN 1024 the #defineArr_size 32 - intSave_to_arg (CharLine[n],Char*Arg[n]) { -memset (ARG,0,sizeof(ARG)); - intHead,tail; + CharTemp[arr_size]; - intPos,index; +index =0; AHead =0; at while(Line[head]! =' /'){ - while(Line[head] = =' '&& Line[head]! =' /'){ -Head + +; - } - if(Line[head] = =' /'){ - Break; in } -Tail =head; to while(Line[tail]! =' '&& Line[tail]! =' /'){ +Tail + +; - } the *pos =0; $memset (temp,0, arr_size);Panax Notoginseng while(Head! =tail) { -Temp[pos] =Line[head]; theHead + +; +POS + +; A } the +Arg[index] = (Char*) Calloc (1, strlen (temp));//arg is a pointer to an array of characters,Must apply for space
If you declare arg to be a two-dimensional array, you do not have to assign it - strcpy (arg[index],temp); $ $Index + +;//!!!!!!!!! - } -Arg[index] =NULL; the returnindex; - }Wuyi intMainintargcConst Char*argv[]) the { - intIndex,len; Wu Char*Arg[n]; - CharLine[n]; About while(Memset (line,0, N), printf (">>"), fgets (line,n,stdin)! =NULL) { $Line[strlen (line)-1] =' /'; - if(line[0] =='\ n'){ - Continue; - } ALen =Save_to_arg (line,arg); + the if(fork () = =0){ - if(EXECVP (arg[0],ARG) = =-1){ $Perror ("Error"); the } the}Else{ the Wait (NULL); the } - } in return 0; the}
- EXECVP () function exit will return 1, by taking its value and judging it, you can implement a prompt message when the user enters a command that is not in the shell.
- In order to implement color when you type ls, you can do the following, Eg:ls-l--color=auto.