-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpleShell.py
More file actions
executable file
·121 lines (96 loc) · 2.91 KB
/
simpleShell.py
File metadata and controls
executable file
·121 lines (96 loc) · 2.91 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
import os
import sys
import fcntl
#-----------------------Redirect-------------------------#
def redirect(file_name, redirect_location):
if redirect_location == 0:
file = os.open(file_name, os.O_RDONLY)
else:
file = os.open(file_name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC) #0644
fcntl.fcntl(file, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
if file == -1:
os.perror("dup2")
exit(1)
sys.stdout.flush()
sys.stdin.flush()
result = os.dup2(file, redirect_location)
if file == -1:
os.perror("dup2")
exit(2)
def is_redirected(exe):
for i in range(len(exe)):
if exe[i] == ">" and i+1 < len(exe):
redirect(exe[i+1], 1)
exe.pop(i)
exe.pop(i)
break
elif exe[i] == "<" and i+1 < len(exe):
redirect(exe[i+1], 0)
exe.pop(i)
exe.pop(i)
break
return exe
def reset_redirection(stdout_save, stdin_save):
sys.stdout.flush()
result = os.dup2(stdout_save, 1)
if result == -1:
os.perror("dup2")
exit(2)
sys.stdin.flush()
result = os.dup2(stdin_save, 0)
if result == -1:
os.perror("dup2")
exit(2)
#---------------------Background------------------------#
#----------------------Get-Input------------------------#
def get_command(stdout_save, stdin_save):
reset_redirection(stdout_save, stdin_save)
return input(os.path.abspath(os.getcwd()) + ": ").split()
#----------------------Commands-------------------------#
def command_exit():
exit()
def command_cd(exe):
if len(exe) == 1:
os.chdir(os.path.expanduser("~"))
else:
os.chdir(exe[2])
def command_status():
print("NOTHING TO SEE HERE")
def command_other(exe_st):
stdin_save = os.dup(0)
stdout_save = os.dup(1)
childExitStatus = -5
spawnpid = os.fork()
if spawnpid == -1:
print("Error")
elif spawnpid == 0:
exe = is_redirected(exe_st)
if exe[0][0] == '#':
exe[0] = ""
if exe[0] != "":
sys.stdout.flush()
os.execvp(exe[0], exe)
os.perror(exe[0])
exit()
else:
reset_redirection(stdout_save, stdin_save)
os.waitpid(spawnpid, 0)
#----------------------Signals------------------------#
#-----------------------Main--------------------------#
def main():
exitStatus = 0
stdin_save = os.dup(0)
stdout_save = os.dup(1)
loop = 0
while(loop < 4):
exe = get_command(stdin_save, stdin_save);
if exe[0] == "exit":
command_exit()
elif exe[0] == "cd":
command_cd(exe)
elif exe[0] == "status":
command_status()
else:
command_other(exe)
loop != 1
main()