Advertisement
Guest User

Untitled

a guest
Feb 21st, 2020
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. #include <iostream>
  4.  
  5. #include <list>
  6.  
  7. #include <cstring>
  8.  
  9. #include <string>
  10.  
  11. #include <thread>
  12.  
  13. using namespace std;
  14.  
  15.  
  16. void initialize() {
  17.   int MAX_LENGTH = 100;
  18.   bool isExecuted = false;
  19.  
  20.   char commandStr[MAX_LENGTH];
  21.   list <string> commandsArray {
  22.     "dir",
  23.     "ls",
  24.     "help",
  25.     "vol",
  26.     "path",
  27.     "tasklist",
  28.     "notepad",
  29.     "echo",
  30.     "color",
  31.     "ping",
  32.   };
  33.  
  34.   // new line indicator
  35.   cout << "\n⇒ ";
  36.  
  37.   // get input from user
  38.   fgets(commandStr, MAX_LENGTH, stdin);
  39.  
  40.   // Stores a copy of original string
  41.   string inputString = commandStr;
  42.  
  43.   // splits strings
  44.   char *argsTok = strtok(commandStr, " ");
  45.  
  46.   while (argsTok != NULL) {
  47.  
  48.     // make sure it's not running
  49.     if (!isExecuted) {
  50.  
  51.         // find command in command list
  52.       for (list<string>::iterator i = commandsArray.begin(); i != commandsArray.end(); i++) {
  53.         if ( *argsTok == *i-> c_str()) {
  54.             // can execute
  55.  
  56.           // create new thread and run command
  57.           thread CreateThread {[&](){
  58.             system(inputString.c_str());
  59.             isExecuted = true;
  60.  
  61.             initialize();
  62.           }};
  63.  
  64.           // wait for thread
  65.                     CreateThread.join();
  66.  
  67.                     // stop searching if executed
  68.           break;
  69.         }
  70.       }
  71.     }
  72.  
  73.     argsTok = strtok(NULL, " ");
  74.   }
  75.  
  76.   // if user types invalid command
  77.     if(!isExecuted) {
  78.     cout << "Unsupported command " << inputString.c_str() << "\n";
  79.     initialize();
  80.   }
  81.  
  82. }
  83.  
  84. int main() {
  85.  
  86.     cout << "Welcome to myShell\n";
  87.  
  88.   initialize();
  89.  
  90.   return (0);
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement