cpp: shell.cpp -- (bugs)

发布时间 2024-01-05 02:40:11作者: lnlidawei

cpp:  shell.cpp -- (bugs)

 

 

 

 

一、原理

 

  1、实现原理:  无限循环 +  标准输入(等待输入状态...);

 

 

 

 

二、代码

 1 [wit@fedora tmp]$ cat  shell.cpp 
 2 #include <iostream>
 3 #include <string>
 4 
 5 using namespace std;
 6 
 7 void output(string o[])
 8 {
 9         string ps = "\033[34m[shell@fedora]$ \033[0m";
10         int j = 0;
11 
12         std::cout << ps << "output: ";
13         while(1)
14         {
15                 if ( o[j]==";;" ) { break; }
16                 std::cout << o[j] << " ";
17                 j++;
18         }
19         std::cout << std::endl;
20         j = 0;
21 }
22 
23 void run()
24 {
25         while(1) {
26 
27                 string buf[101];
28                 string ps = "\033[34m[shell@fedora]$ \033[0m";
29                 string t = "";
30 
31                 int i = 0;
32                 cout << ps << "input: ";
33                 while(1)
34                 {
35                         cin >> t;
36                         buf[i] = t;
37                         i++;
38                         if ( t==";;" ) { break; }
39                         if ( t=="exit" || t=="quit" ) { t="quit"; break; }
40                 }
41                 i = 0;
42 
43                 output(buf);
44 
45                 if( t=="exit" || t=="quit" ) { break; }
46         }
47 }
48 
49 int main(int argc, char *argv[], char *envp[])
50 {
51 
52         run();
53 
54         return 0;
55 
56 }
57 [wit@fedora tmp]$ 
58 [wit@fedora tmp]$ 

 

 

三、运行

 1 [wit@fedora tmp]$ alias | grep gpp
 2 alias gpp='g++ -g -Wall -std=c++20 -o'
 3 [wit@fedora tmp]$ 
 4 [wit@fedora tmp]$ 
 5 [wit@fedora tmp]$ gpp shell shell.cpp && ./shell
 6 [shell@fedora]$ input: hello world ;;
 7 [shell@fedora]$ output: hello world 
 8 [shell@fedora]$ input: hello six mp5 c4 awp ;;
 9 [shell@fedora]$ output: hello six mp5 c4 awp 
10 [shell@fedora]$ input: exit ;;
11 Segmentation fault (core dumped)
12 [wit@fedora tmp]$ 

 

 

四、参考资料:

 

  1、【Linux】bash项目mybash的实现  https://blog.csdn.net/qq_53830608/article/details/127518949?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-1-127518949-blog-70148939.235%5Ev40%5Epc_relevant_rights_sort&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-1-127518949-blog-70148939.235%5Ev40%5Epc_relevant_rights_sort&utm_relevant_index=2

 

  2、GNU bash实现机制与源代码简析  https://www.cnblogs.com/napoleon_liu/archive/2011/04/01/2001886.html