#!/usr/bin/python from os import * import sys def GetCommand(prompt): cmd = raw_input(prompt) path = cmd.split(" ", 1)[0] return(cmd, path) def Run(): (cmd, path) = GetCommand("What command do you want to run? ") pid = fork() if pid == 0 : execvp(path, cmd.split()) else: wait() def Pipe(): (cmd1, path1) = GetCommand("What is the first command? ") (cmd2, path2) = GetCommand("What is the second command? ") pid = fork() if pid == 0: (readEnd, writeEnd) = pipe() pid = fork() if pid == 0: dup2(readEnd, 0) close (writeEnd) execvp(path2, cmd2.split()) else: dup2(writeEnd, 1) close(readEnd) execvp(path1, cmd1.split()) else : waitpid(pid,0) def Redirect(): inFile = raw_input("What is the input file? "); outFile = raw_input("What is the output file? "); (cmd, path) = GetCommand("What command do you want to run? ") pid = fork() if pid == 0: if inFile != "": inFD = open(inFile, O_RDONLY) dup2(inFD, 0) if outFile != "": outFD = open(outFile, O_WRONLY|O_CREAT|O_TRUNC, 0o644) dup2(outFD, 1) execvp(path, cmd.split()) else: wait() def Error(command): print "Unknown command ", command print "Known commands are RUN, PIPE, REDIRECT, QUIT" command = raw_input("Enter a command: ") while command != "QUIT": print "Executing ", command if command == "RUN": Run() elif command =="PIPE": Pipe() elif command == "REDIRECT": Redirect() else : Error(command) print command = raw_input("Enter a command: ")