This is the basic layout of a toy shell.
Each of the following steps will be detailed below.
int main() { bool keepLooping = true; while(keepLooping) { 1 - GRAB THE COMMAND LINE 2 - PARSE THE COMMAND LINE 3 - ERROR CHECK COMMAND LINE if(/*command is exit*/) { keepLooping = false; } else { 3 - FORK 4 - PARENT PROCESS: 4.1 - WAIT FOR CHILD 5 - CHILD PROCESS: 5.1 - EXECL } } return 0; }
The following code can be used to grab a line text from the command line.
The entire line of text upto the \n will be put into the buffer.
char buffer[256]; cin.getline(buffer, 256);
The following code is an example of parsing a commmand line.
This code uses strtok_s to grab the elements from the buffer 1 at a time.
This code can be modified to form a set of arguements that can be passed to the execl function.
char* token; char* nextToken; token = strtok_s(buffer, " ", &nextToken); while(token != NULL) { token = strtok_s(NULL, " ", &nextToken); }
Here is the same example with strtok
char* token; token = strtok(buffer, " "); while(token != NULL) { token = strtok(NULL, " "); }STRTOK Webpage
This code loops through the command line and puts each successive element of the command line into token
As you grab the tokens one at a time you can decide what you want to do with them.
There is only 1 special token you have to handle. The > token.
> is the redirection token and your program should handle it the same way unix does. Redirect STDOUT to the specified file.
EXAMPLE:
cat someFile.txt > double.txt
Normally cat would print someFile.txt to the screen but the > token forces the output to a file called double.txt instead.
Have the parent wait() on the child process.
Use your preferred version of execl to execute the command line.
Lab
Page On Fork() and Execl()