-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathos.py
More file actions
371 lines (317 loc) · 13.2 KB
/
os.py
File metadata and controls
371 lines (317 loc) · 13.2 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#PART 1
import os
import sys
import subprocess
import signal
import shlex
from pathlib import Path
import platform
class BasicShell:
def __init__(self):
self.history = []
self.jobs = {}
self.job_counter = 0
self.running = True
# Setup signal handlers (Windows-compatible)
signal.signal(signal.SIGINT, self.handle_sigint)
# SIGCHLD only exists on Unix/Linux, skip on Windows
if platform.system() != 'Windows':
signal.signal(signal.SIGCHLD, self.handle_sigchld)
def handle_sigint(self, signum, frame):
"""Handle Ctrl+C (SIGINT) - don't exit shell"""
print("\n")
self.display_prompt()
def handle_sigchld(self, signum, frame):
"""Handle child process termination (SIGCHLD) - Unix only"""
try:
while True:
pid, status = os.waitpid(-1, os.WNOHANG) #checks if any child process has ended
if pid == 0:
break
# Remove completed background job
for job_id, job_info in list(self.jobs.items()):# iterates through jobs to find completed one
if job_info['pid'] == pid:
print(f"\n[{job_id}] Done {' '.join(job_info['command'])}")
del self.jobs[job_id]
break
except (ChildProcessError, AttributeError):
pass
def check_background_jobs(self): #check background jobs status if on Windows
"""Check status of background jobs (Windows-compatible)"""
for job_id, job_info in list(self.jobs.items()):
if job_info['process'].poll() is not None:
print(f"\n[{job_id}] Done {' '.join(job_info['command'])}")
del self.jobs[job_id]
def display_prompt(self):
"""Display shell prompt"""
cwd = os.getcwd()
home = str(Path.home())
if cwd.startswith(home):
cwd = cwd.replace(home, '~', 1)
print(f"\n{cwd} $ ", end='', flush=True)
def parse_input(self, user_input):# Parse user input and return list of commands with pipes
"""Parse user input and return list of commands with pipes"""
if not user_input.strip():
return None
# Check for background process
background = False
if user_input.strip().endswith('&'):
background = True
user_input = user_input.rstrip('&').strip()
# Split by pipe
commands = []
for cmd in user_input.split('|'):
cmd = cmd.strip()
if cmd:
commands.append(self.parse_command(cmd))
return {'commands': commands, 'background': background}
def parse_command(self, command):
"""Parse a single command for I/O redirection"""
tokens = shlex.split(command)
cmd_args = []
stdin_file = None
stdout_file = None
stdout_append = False
i = 0
while i < len(tokens):
if tokens[i] == '<':
if i + 1 < len(tokens):
stdin_file = tokens[i + 1]
i += 2
else:
raise ValueError("Syntax error: expected filename after '<'")
elif tokens[i] == '>':
if i + 1 < len(tokens):
stdout_file = tokens[i + 1]
stdout_append = False
i += 2
else:
raise ValueError("Syntax error: expected filename after '>'")
elif tokens[i] == '>>':
if i + 1 < len(tokens):
stdout_file = tokens[i + 1]
stdout_append = True
i += 2
else:
raise ValueError("Syntax error: expected filename after '>>'")
else:
cmd_args.append(tokens[i])
i += 1
return {
'args': cmd_args,
'stdin': stdin_file,
'stdout': stdout_file,
'append': stdout_append
}
#PART 2
def execute_builtin(self, command):
"""Execute built-in commands"""
args = command['args']
cmd = args[0]
if cmd == 'exit':
print("Exiting shell...")
self.running = False
return True
elif cmd == 'cd':
try:
if len(args) == 1:
os.chdir(str(Path.home()))
else:
os.chdir(args[1])
except FileNotFoundError:
print(f"cd: {args[1]}: No such file or directory")
except PermissionError:
print(f"cd: {args[1]}: Permission denied")
except Exception as e:
print(f"cd: error: {e}")
return True
elif cmd == 'pwd':
print(os.getcwd())
return True
elif cmd == 'history':
for i, cmd in enumerate(self.history, 1):
print(f"{i:4d} {cmd}")
return True
elif cmd == 'jobs':
# Check for completed jobs first
self.check_background_jobs()
if not self.jobs:
print("No background jobs")
else:
for job_id, job_info in self.jobs.items():
print(f"[{job_id}] Running {' '.join(job_info['command'])}")
return True
elif cmd == 'fg':
if not self.jobs:
print("fg: no current job")
return True
# Get job to bring to foreground
if len(args) > 1:
try:
job_id = int(args[1])
if job_id not in self.jobs:
print(f"fg: {job_id}: no such job")
return True
except ValueError:
print(f"fg: {args[1]}: invalid job specification")
return True
else:
job_id = max(self.jobs.keys())
job_info = self.jobs[job_id]
print(f"{' '.join(job_info['command'])}")
try:
# Wait for process to complete
job_info['process'].wait()
del self.jobs[job_id]
except Exception as e:
print(f"fg: error: {e}")
if job_id in self.jobs:
del self.jobs[job_id]
return True
elif cmd == 'help':
print("\n" + "="*70)
print(" BASIC SHELL - BUILT-IN COMMANDS")
print("="*70)
print(" cd [dir] Change directory (default: home)")
print(" pwd Print working directory")
print(" exit Exit the shell")
print(" history Show command history")
print(" jobs List background jobs")
print(" fg [job_id] Bring background job to foreground")
print(" help Show this help message")
print("\n FEATURES:")
print(" I/O Redirection: cmd < input.txt")
print(" cmd > output.txt")
print(" cmd >> output.txt")
print(" Piping: cmd1 | cmd2 | cmd3")
print(" Background: cmd &")
print("="*70 + "\n")
return True
elif cmd == 'clear' or cmd == 'cls':
os.system('cls' if platform.system() == 'Windows' else 'clear')
return True
return False
#PART 3
def execute_external(self, parsed_input):
"""Execute external commands with piping and I/O redirection"""
commands = parsed_input['commands']
background = parsed_input['background']
# Check if it's a built-in command (only for single commands)
if len(commands) == 1 and not background:
if self.execute_builtin(commands[0]):
return
try:
processes = []
prev_stdout = None
stdin_handle = None
stdout_handle = None
for i, command in enumerate(commands):
args = command['args']
if not args:
continue
# Setup stdin
if command['stdin']:
stdin_handle = open(command['stdin'], 'r')
stdin = stdin_handle
elif i > 0:
stdin = prev_stdout
else:
stdin = None
# Setup stdout
if command['stdout']:
mode = 'a' if command['append'] else 'w'
stdout_handle = open(command['stdout'], mode)
stdout = stdout_handle
elif i < len(commands) - 1:
stdout = subprocess.PIPE
else:
stdout = None
# Create process with shell=True for Windows compatibility
if platform.system() == 'Windows':
process = subprocess.Popen(
' '.join(args),
stdin=stdin,
stdout=stdout,
stderr=subprocess.PIPE,
shell=True
)
else:
process = subprocess.Popen(
args,
stdin=stdin,
stdout=stdout,
stderr=subprocess.PIPE
)
processes.append(process)
# Close previous pipe
if prev_stdout and prev_stdout != stdin_handle:
prev_stdout.close()
# Save stdout for next command in pipeline
if stdout == subprocess.PIPE:
prev_stdout = process.stdout
# Handle background vs foreground execution
if background:
self.job_counter += 1
self.jobs[self.job_counter] = {
'pid': processes[-1].pid,
'process': processes[-1],
'command': [arg for cmd in commands for arg in cmd['args']]
}
print(f"[{self.job_counter}] {processes[-1].pid}")
else:
# Wait for all processes to complete
for process in processes:
stdout, stderr = process.communicate()
if stderr:
error_msg = stderr.decode().strip()
if error_msg:
print(error_msg, file=sys.stderr)
# Close file handles
if stdin_handle:
stdin_handle.close()
if stdout_handle:
stdout_handle.close()
except FileNotFoundError:
print(f"shell: {args[0]}: command not found")
except PermissionError:
print(f"shell: {args[0]}: permission denied")
except Exception as e:
print(f"shell: error: {e}")
def run(self):
"""Main shell loop"""
print("=" * 70)
print(" BASIC SHELL IMPLEMENTATION - OPERATING SYSTEMS PROJECT")
print("=" * 70)
print(f" Platform: {platform.system()}")
print(" Built-in Commands: cd, pwd, exit, history, jobs, fg, help, clear")
print(" Features: I/O redirection (<, >, >>), piping (|), background (&)")
print(" Type 'help' for more info or 'exit' to quit")
print("=" * 70)
while self.running:
try:
# Check background jobs status
self.check_background_jobs()
self.display_prompt()
user_input = input()
if not user_input.strip():
continue
# Add to history
self.history.append(user_input)
# Parse and execute
parsed_input = self.parse_input(user_input)
if parsed_input:
self.execute_external(parsed_input)
except EOFError:
print("\nExiting shell...")
break
except KeyboardInterrupt:
print()
continue
except Exception as e:
print(f"shell: error: {e}")
def main():
"""Entry point"""
shell = BasicShell()
shell.run()
if __name__ == "__main__":
main()