Assignment 8, due Apr 7

Part of the homework for 22C:50, Spring 2003
by Douglas W. Jones
THE UNIVERSITY OF IOWA Department of Computer Science

Always, on every assignment, please write your name legibly as it appears on your University ID and on the class list!

Homework

Do problems 4, 6, 11 and 13 from the end of Chapter 11 (1 point each).

Machine Problem 5

Due April 11

Write a command shell to run under Unix, to be known as MP5sh, with the executable named mp5. Your solution should be in a directory called mp5, and this should include the mp5 source and executable.

The MP5sh command language is:

<script> ::= { <line> } <EOF>
<line> ::= <progname> { <argument> } <EOL>
<line> ::= # { <anything> } <EOL>
<progname> ::= <nonblankstring>
<argument> ::= <nonblankstring>

Blanks separate nonblank strings; all well-formed lines end with <EOL> all files end with <EOF> (the C programming language has special representations for these special items). Tabs are blanks for the purpose of this definition. Note that lines under the MP5sh shell that begin with a pound-sign are comments, as in tcsh and the other Unix shells, and note that the MP5sh shell does not support any I/O redirection or other interesting features -- you could add those later.

To launch a program under Unix from a C or C++ program, you do the following bit of bizarre code:

        int pid;
        int status;
        char filename[];
        char * argv[];
        int argc;
	extern char **environ;

	if ((pid = fork()) == 0) {
		execve( filename, argv, environ );
		fputs( argv[0], stderr );
		fputs( ": could not execute\n", stderr );
		exit();
	} else {
		while (wait( &status ) != pid) ;
        }

Note that the argv array must have at least one entry that is NULL; all entries before this are pointers to the first characters of arguments, and the first entry is a pointer to the program name itself.

Also note that the execve() command needs the real filename of the binary file from which you want to execute code. Where the tcsh shell will accept echo for example, your shell will require you to type either /bin/echo or /usr/bin/echo depending on what Unix system you use. You can use the whereis x command to find the real file name for any shell command x.

For extra credit or honors: After you get your shell to work, modify it so that, when the user's command name does not contain a slash, if the command cannot be directly executed, it tries prefixing it with /bin and then with /usr/bin (this will make the shell behave in a manner similar to the built in UNIX shells, with their search of all the directories in $PATH.

Alternatively or in addition: Make the shell accept command line argments, so if you run it as mp5 script it will open the file named script and read command lines from there. You'll find an elaborate getmyargs function in the code for mp1 that is overkill for this problem but that illustrates how command line options work.