Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import parse
- import sys
- import os
- EXIT_SUCCESS = 0
- EXIT_FAILURE = 1
- # Internal change-directory command.
- def shell_cd (dir):
- os.chdir(dir)
- # Internal exit/quit command.
- def shell_exit(code):
- sys.exit(code)
- # Execute simple command
- def run_simple_command (simple_commands_list, father_command):
- cmd = simple_commands_list[0].word
- if cmd == 'exit' or cmd == 'quit':
- shell_exit(EXIT_SUCCESS)
- args = []
- for i in range(0, len(simple_commands_list)):
- args.append(simple_commands_list[i].word)
- if cmd == 'cd':
- shell_cd(args[1])
- return EXIT_SUCCESS
- try:
- pid = os.fork()
- if pid == -1:
- # error forking
- return EXIT_FAILURE
- elif pid == 0:
- # child process
- st = os.execvp("/bin/" + cmd, args)
- #st = os.execvp(command, args)
- # only if exec failed
- # os._exit(st)
- else:
- os.waitpid(pid, 0)
- #only parent process gets here
- # status = os.waitpid(pid, 0)
- # if os.WIFEXITED(status):
- # print("Child {} terminated normally, with code {}".format(pid, os.WEXITSTATUS(status)))
- # return status
- return EXIT_SUCCESS
- except Exception as e:
- print("Error: {}".format (e))
- # TODO - extract command and arguments; ATTENTION! not all commands are simple_commands
- # TODO - extract redirects from father_command ???
- # TODO - fork parent process
- # TODO - execute child
- # TODO - wait for child
- # TODO - return exit status
- # Process two commands in parallel, by creating two children.
- def do_in_parallel (cmd1, cmd2, father_command):
- # TODO - execute cmd1 and cmd2 simultaneously
- pass
- def do_on_pipe (cmd1, cmd2, father_command):
- # TODO - redirect the output of cmd1 to the input of cmd2
- pass
- #Parse and execute a command.
- def parse_command (command):
- if command.op == parse.OP_NONE:
- # TODO - run a simple command
- return run_simple_command (command.commands, command)
- elif command.op == parse.OP_SEQUENTIAL:
- # TODO - execute the commands one after the other
- pass
- elif command.op == parse.OP_PARALLEL:
- # TODO - execute the commands simultaneously
- pass
- elif command.op == parse.OP_CONDITIONAL_NZERO:
- # TODO - execute the second command only if the first one returns non zero
- pass
- elif command.op == parse.OP_CONDITIONAL_ZERO:
- # TODO - execute the second command only if the first one returns zero
- pass
- elif command.op == parse.OP_PIPE:
- # TODO - redirect the output of the first command to the input of the second
- return 0 # TODO - replace with actual exit code of command
- fileName = sys.argv[1]
- fileHandle = open(fileName, "r")
- for line in fileHandle:
- command = parse.parse(line)
- #parse.dump(command) # TODO - delete the line before submitting the homework
- parse_command(command)
- fileHandle.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement