Question: Write a C program, mysh, which simulates the Unix sh for command processing. Your mysh should run as follows: 1. Prompt for an input line,
Write a C program, mysh, which simulates the Unix sh for command processing. Your mysh should run as follows: 1. Prompt for an input line, which is of the form cmd arg1 arg2 arg3 .... argn where cmd is a command. Valid commands include "cd", "exit", and ANY Unix binary executables, e.g. echo, ls, date, pwd, cat, cp, mv, cc, vi, emacs, etc. 2. Handle simple commands: cmd = "cd" : chdir(arg1) OR chdir($HOME) if no arg1; cmd = "exit" : exit(1) to terminate; NOTE: chdir(pathname) is a syscall to change CWD. $HOME is the home directory; YOU must find its value from *env[ ]. 3. For all other commands: fork a child process; wait for the child to terminate; print child's exit status code continue step 1; 4. Child process: First, assume NO pipe in command line: 4-1. Handle I/O redirection: cmd arg1 arg2 ... < infile // take inputs from infile cmd arg1 arg2 ... > outfile // send outputs to outfile cmd arg1 arg2 ... >> outfile // APPEND outputs to outfile 4-2. Execute cmd by execve(), passing parameters char *myargv[], char *env[] to the cmd file, where myargv[ ] is an array of char * with myargv[0]->cmd, myargv[1]->arg1, ..... Ending with NULL pointer 4-2. NOTE: your myargv[] must be passed correctly, as in cmd one two three Then in the cmd program, argc=4, myargv[0]="cmd", myargv[1]="one", etc. 5. After YOUR mysh works for simple commands, extend it to handle PIPE. If the command line has a | symbol: divide it into head and tail: e.g. cmd1 < infile | cmd 2 > outfile head = "cmd < infile"; tail = "cmd 2 > outfile" Then consult the pipe example code in the class notes to see HOW TO create a pipe fork a child process to share the pipe arrange one process as the pipe writer, and the other process as the pipe reader. Then, let each process execve() to its command (possibly with I/O redirection). 7. For sh scripts files: Assume the first line of every sh script begin with #! /usr/bin/bash open the file for READ; read 256 chars from file beginning to a char buf[256]; close the opened file strncmp(buf, "#!", 2) to check whether the first 2 chars are #!; if so, cmd = "/usr/bin/bash", myargv[0]="bash", argv[1]="filename"; Then execve(cmd, myargv, env);
If you could comment your code with brief explanations as to what crucial lines of code do that would be deeply appreciated.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
