Shell is a program for managing processes and running programs. All common shells have three main functions.
(1) run the program
Grep, date, ls, ECHO, and mail are common programs written in C and compiled into machine languages. Shell loads them into memory and runs them. Many people regard shell as a program starter.
(2) Manage Input and Output
Use the <,>, and | symbols to redirect input and output. In this way, you can tell shell to connect the input and output of processes to a file or other processes.
(3) Programming
Shell is also a programming language with variables and flow control.
The main loop of a shell mainly executes the following four steps:
(1) enter a. Out;
(2) Shell creates a new process to run this program;
(3) Shell loads programs from the disk;
(4) The program runs in its process until it ends.
1 #include <stdio.h> 2 #include <signal.h> 3 #include <string.h> 4 #include <stdlib.h> 5 6 #define MAXARGS 20 7 #define ARGLEN 100 8 9 int main()10 {11 char *arglist[MAXARGS+1];12 int numargs;13 char argbuf[ARGLEN];14 char *makestring();15 numargs = 0;16 17 while (numargs < MAXARGS)18 {19 printf("Arg[%d]? ", numargs);20 if (fgets(argbuf, ARGLEN, stdin) && *argbuf != ‘\n‘)21 arglist[numargs++] = makestring(argbuf);22 else23 {24 if (numargs > 0)25 {26 arglist[numargs] = NULL;27 execute(arglist);28 numargs = 0;29 }30 }31 }32 return 0;33 }34 35 int execute(char *arglist[])36 {37 execvp(arglist[0], arglist);38 perror("execvp failed");39 exit(1);40 }41 42 char *makestring(char *buf)43 {44 char *cp;45 buf[strlen(buf)-1] = ‘\0‘;46 cp = malloc(strlen(buf)+1);47 if (cp == NULL)48 {49 fprintf(stderr, "no memory\n");50 exit(1);51 }52 strcpy(cp, buf);53 return cp;54 }
Processes and Programs: write command interpreter SH (1)