Assignment 2 Solutions

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

  1. Background: The C source file http://homepage.cs.uiowa.edu/~dwjones/opsys/shell.txt Contains a working command shell that should work under most Unix systems.

    a) There are 4 #include directives. Each of them makes some of the function calls in the program legal. Which functions does each include directive make legal? An empirical approach may be the easiest way to answer this -- see what error messages result from deleting each #include directive. (0.5 points)

    stdio.h is needed to define EOF, stdout and stderr as well as the routines getchar() and fputs().

    string.h is needed to define strncpy() and strncat().

    stdlib.h is needed to define exit().

    fcntl.h does not seem to serve any purpose in this program.

    b) The code exit(0) is used to exit the shell when it hits an end-of-file or when it encounters an exit command. The Unix standard discourages using this naked constant, and recommends that exit() be called with specific symbolic constants indicating success and failure. What are the recommended constants and which header file are they in? Hint: It's the same header file that allows you to call exit() in the first place. (0.5 points)

    EXIT_SUCCESS is recommended for success, and EXIT_FAILURE is recommended for everything else.

  2. Background: Consider this shell script, stored in the executable file script:
    # script
    script | script
    

    a) What does it do? Answer this by reading the text. (0.5 points)

    Each call to script causes two calls to script. These are connected by the vertical bar connector, called a pipe in Unix. Unfortunately, the two shell commands on each side of a shell pipe are executed in parallel, and this means that the script script causes an unbounded number of processes to try to run in parallel. This can cause system crashes!

    Unfortunately, there's a pre-existing shell command called script. Those who answered the question in terms of that command were given credit for correctly explaining the strange (and rather problematic) behavior of the built-in script command when launched with this launcher.

    b) Why, on early Unix systems, did it crash the system? Trying it might help answer this. (0.5 points)

    It launches an unbounded number of processes.

  3. A Problem Write a shell script that, given an integer argument i outputs the successive integers 1 to i. (1 point)

    As with all programming problems, there are an infinite number of solutions. Here is one:

    #!/bin/tcsh
    # thisscript i
    #    outputs successive integers from 1 to i
    @ count = 0
    while ( $count < $1 )
            @ count ++
            echo $count
    end