Commands in Linux are divided into two types: Internal commands and external commands. Internal commands are implemented by Shell programs, such as cd and echo. Linux has a limited number of internal commands, and most of them are rarely used. Every Linux external command is a separate application. The vast majority of commands such as ls and cp, which we are very familiar with, are external commands that can exist in the form of executable files, most of them are stored in the directory/bin and/sbin. In this way, the difficulty of programming can be greatly reduced. We only need to implement limited internal commands and execute all other inputs as applications.
//MyShell.c
# Include
# Include
# Include
# Include
# Include
# Define MAXSIZE 100 void info_print (); int main (int argc, char const * argv []) {/* code */while (1) {char command [MAXSIZE]; pid_t pid; int status; info_print (); bzero (command, MAXSIZE); gets (command); if (-1 = (pid = fork ())) {perror (fork); exit (-1) ;}if (pid> 0) {wait (& status) ;}else {int I, flag = 0, j = 0; char * file, * argv [10]; file = command; argv [flag ++] = command; for (I = 0; command [I]! = ''; I ++) {while (command [I] ='') {command [I ++] = ''; j = 1 ;} if (1 = j) {argv [flag ++] = command + I; j = 0 ;}} argv [flag] = NULL; if (0 = strncmp (file, cd, 2) {// printf (OK % s, argv [1]); if (-1 = chdir (argv [1]) {perror (chdir); exit (-1) ;}} else {if (-1 = execvp (file, argv) {// perror (execvp); fprintf (stderr, % s: command not found, file) ;}}} return 0;} void info_print ()
// Print the prompt information{Char buf [MAXSIZE], * username, hostname [MAXSIZE], pwd [MAXSIZE], ch; bzero (buf, MAXSIZE); bzero (pwd, MAXSIZE); bzero (hostname, MAXSIZE); if (NULL = (username = getenv (USER) {printf (Error: get username failure !); Exit (-1);} if (NULL = getcwd (pwd, MAXSIZE) {perror (getcwd); exit (-1 );} if (-1 = gethostname (hostname, MAXSIZE) {perror (gethostname); exit (-1) ;}if (0 = strcmp (username, root )) {ch = '#';} else {ch = '$';} sprintf (buf, % s @ % s: % s % c, username, hostname, pwd, ch); fprintf (stdout, % s, buf );}