Repository navigation
Expand file tree
/
Copy pathShell.java
More file actions
123 lines (104 loc) · 2.48 KB
/
Copy pathShell.java
File metadata and controls
123 lines (104 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import java.util.*;
public class Shell
{
public static native int changeDirectory(String s);
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String cmd;
ArrayList<String> argv;
System.loadLibrary("chdir");
while(true)
{
System.out.print("> ");
cmd = input.nextLine();
if(cmd.isEmpty())
continue;
argv = parse(cmd);
if(argv.isEmpty())
continue;
else if(shbins(argv))
continue;
shexec(argv);
}
}
public static ArrayList<String> parse(String s)
{
String ps = new String();
ArrayList<String> argv = new ArrayList<String>();
int i;
for(i = 0; i < s.length(); i++)
switch(s.charAt(i))
{
case ';':
if(argv.isEmpty())
break;
else if(shbins(argv))
{
argv.clear();
break;
}
shexec(argv);
argv.clear();
break;
case ' ':
break;
default:
for(; i < s.length() && s.charAt(i) != ' '; i++)
ps += s.charAt(i);
argv.add(ps);
ps = new String();
}
return argv;
}
public static void shexec(ArrayList<String> argv)
{
try
{
String[] cmd_arr = new String[argv.size()];
Runtime shcmd = Runtime.getRuntime();
Process shproc = shcmd.exec(argv.toArray(cmd_arr));
int pchar;
while((pchar = shproc.getInputStream().read()) > 0)
System.out.print((char) pchar);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public static boolean shbins(ArrayList<String> bcmd)
{
String[] bcmds = { "exit", "chdir" };
int i;
for(i = 0; i < bcmds.length; i++)
if(bcmds[i].compareTo(bcmd.get(0)) == 0)
{
switch(i)
{
case 0:
{
Runtime shexit = Runtime.getRuntime();
shexit.exit(0);
}
case 1:
if(bcmd.size() == 1)
changeDirectory(System.getenv("HOME"));
else
{
String dir = new String();
int j;
for(j = 0; j < bcmd.size() - 1; j++)
if(j > 0)
dir += ' ' + bcmd.get(j + 1);
else
dir = bcmd.get(j + 1);
if(changeDirectory(dir) < 0)
System.err.println(dir + ": No such directory.");
}
}
return true;
}
return false;
}
}