Simulate the implementation of the shell, so that it supports the redirection function

We all know that users operate our hardware or software through the operating system, but we usually do not communicate directly with the operating system when we use the computer. Under linux, we usually enter commands through the terminal, but have you ever wondered why the operating system can recognize when we enter commands in the terminal? There is a command line interpreter shell, which is the so-called shell program, to interpret the commands we enter, call the relevant system call interface, and realize various operations. Here we will simulate a shell.

To simulate a shell, we first need to know how the shell works: when we open the terminal, we also load the shell process into memory, and for each command we enter, it is an executable program , that is, the child process generated by our shell process through the fork() system call. The shell process itself will not execute our command function, but let its child process perform the corresponding operation, while itself is Wait for the child process to return to reclaim the resources of the child process.

To simulate the realization of the shell, it must be as close as possible to the function of the shell, and there is one function of the shell that needs attention, that is, output redirection.

For our output redirection, it is nothing more than relocating our output on the display file to our file, so here we only need to close the file descriptor "1", and then open our file (the file Descriptor 1------stdout (originally output to the display file))

code show as below:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<ctype.h>
int main(){
while(1){
pid_t pid = fork();
if(pid == 0){
printf("[Myshell@localhost]$");
fflush(stdout);
char buf[1024];
ssize_t readnum  = read(0,buf,sizeof(buf)-1);
if(readnum > 0){
buf[readnum-1] = 0;//处理'\0'
}
char* start = buf;
char* argv[32];
memset(argv,0,32);
argv[0] = start;
ssize_t index = 1;
while(*start){
if(isspace(*start)){
*start = '\0';
start++;
if(*start == '>'){
start++;
while(isspace(*start)){
start++;
}
char filename[32];
int idx = 0;
while(!isspace(*start)&&*start!='\0'){
filename[idx] = *start;
idx++;
start++;
}
filename[idx] = '\0';
close(1);
int fd = open((const char*)filename,O_WRONLY|O_CREAT,0644);
}
else
argv[index++] = start;
}
else{
start++;
}


}
argv[index] = NULL;
execvp(argv[0],argv);
exit(1);
}
else{
waitpid(pid,NULL,0);
}
}
return 0;

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324525894&siteId=291194637