








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









You will learn how to write a UNIX shell program. This will give you the opportunity to learn how child processes are created to perform large-grained work and how the parent process can follow up on a child process's work.
A shell, or command line interpreter program, is a mechanism with which each interactive user can send commands to the OS and by which the OS can respond to the user. Whenever a user has successfully logged in to the computer, the OS causes the user process assigned to the login port to execute a specific shell. The OS does not ordinarily have a built-in window interface. Instead, it assumes a simple character-- oriented interface in which the user types a string of characters (terminated by pressing the Enter or Return key) and the OS responds by typing lines of characters back to the screen. If the human-computer interface is to be a graphical windows interface, then the software that implements the window manager subsumes the shell tasks that are the focus of this exercise. Thus the character-oriented shell assumes a screen display with a fixed number of lines (usually 25) and a fixed number of characters (usually 80) per line. Once the shell has initialized its data structures and is ready to start work, it clears the 25-line display and prints a prompt in the first few character positions on the first line. Linux systems are usually configured to include the machine name as part of the prompt. For example, my Linux machine is named kiowa.cs.colorado.edu, so the shell prints, as its prompt string: kiowa> or bash> depending on which shell I am using. The shell then waits for the user to type a command line in response to the prompt. The command line could be a string such as: kiowa> ls – al terminated with an
Every shell has its own language syntax and semantics. In the standard Linux shell, bash , a command line has the form: command [arg1] [arg2] ... [argN] in which the first word is the command to be executed and the remaining words are arguments expected by that command. The number of arguments depends on which command is being executed. For example, the directory listing command may have no arguments-simply by the user's typing “ ls ” or it may have arguments prefaced by the negative “ - “ character, as in “ ls – al” , where “ a ” and “ l ” are arguments. The command determines the syntax for the arguments, such as which of the arguments may be grouped (as for the “ a ” and “ l ” in the “ ls ” command), which arguments must be preceded by a " - " character, and whether the position of the argument is important. Other commands use a different argument-passing syntax. For example, a g++ compiler command might look like: kiowa> g++ - g - o deviation - S main.cpp inout.cpp – lmath in which the arguments g, o deviation, S, main.cpp, inout.cpp, and lmath are all passed to the C++ compiler, g++. The shell relies on an important convention to accomplish its task: The command for the command line is usually the name of a file that contains an executable program, for example, “ ls ” and “ g++ ” (files stored in /bin on most UNIX-style machines). In a few cases, the command is not a filename but rather a command that is implemented within the shell. For example, “ cd ” (change directory) is usually implemented within the shell itself rather than in a file in /bin. Because the vast majority of the commands are implemented in files, you can think of the command as actually being a filename in some directory on the machine. This means that the shell's job is to: 1 - find the file 2 - prepare the list of parameters for the command, 3 - cause the command to be executed using the parameters. Many shell programs are used with UNIX variants, including the original Bourne shell ( sh ), the C shell (csh) with its additional features over sh , the Korn shell, and the standard Linux shell (bash). All have followed a similar set of rules for command line syntax, though each has a superset of features.
The Bourne shell is described in Ritchie and Thompson's original UNIX paper [Ritchie and Thompson, 1974]. As described in the previous subsection, the shell should accept a command line from the user, parse the command line, and then invoke the OS to run the specified command with the specified argu- ments. This command line is a request to execute the program in any file that contains a program, including programs that the user wrote. Thus a programmer can write an ordinary C program, compile it, and have the shell execute it just like it was a UNIX command. For example, suppose that you write a C++ program in a file named main.cpp and then compile and execute it with shell commands such as: kiowa> g++ - c – I. – o main.o main.cpp kiowa> g++ - o main.o main kiowa> ./main
When these three system calls are used, here is the code skeleton that a shell might use to execute a command: // Child if (fork() == 0) { execvp(fullpathname, argv); } // Parent else { int status=0; wait(&status); cout << "Child exited with status of " << status << endl; }
In the normal paradigm for executing a command, the parent process creates a child process, starts it executing the command, and then waits until the child process terminates. If the "and" (" & ") operator is used to terminate the command line, then the shell is expected to create the child process and start it ex- ecuting on the designated command but not have the parent wait for the child to terminate. That is, the parent and the child will execute concurrently. While the child executes the command, the parent prints another prompt to stdout and waits for the user to enter another command line. If the user starts several commands, each terminated by an " & ", and each takes a relatively long time to execute, then many processes can be running at the same time. When a child process is created and started executing on its own program, both the child and the parent expect their stdin stream to come from the user via the keyboard and for their stdout stream to be written to the character terminal display. Notice that if multiple child processes are running concurrently and all expect the keyboard to define their stdin stream, then the user will not know which child process will receive data on its stdin if data is typed to the keyboard. Similarly, if any of the concurrent processes write characters to stdout , those characters will be written to the terminal display wherever the cursor happens to be positioned. The kernel makes no provision for giving each child process its own keyboard or terminal (unlike a windows system, which controls the multiplexing and demultiplexing through explicit user actions).
A process, when created, has three default file identifiers: stdin , stdout , and stderr. These three file identifiers correspond to the C++ objects cin , cout , and cerr. If the process reads from stdin (using cin ) then the data that it receives will be directed from the keyboard to the stdin file descriptor. Similarly, data received from stdout (using cout ) and stderr (using cerr ) are mapped to the terminal display. The user can redefine stdin or stdout whenever a command is entered. If the user provides a filename argument to the command and precedes the filename with a “less than” character " < ” then the shell will substitute the designated file for stdin ; this is called redirecting the input from the designated file.
A similar set of calls is used if you want to redirect stdout to an output file: int newstdout = open(“program.stats”,O_WRONLY|O_CREAT,S_IRWXU|S_IRWXG|S_IRWXO); close(1); dup(newstdout); close(newstdout); Make sure that when you use this open call you include ALL of the flags I’ve listed here. Otherwise the redirection won’t work.
The pipe is a common IPC mechanism in Linux and other versions of UNIX. By default, a pipe employs asynchronous send and blocking receive operations. Optionally, the blocking receive operation may be changed to be a nonblocking receive. Pipes are FIFO (first-in/first out) buffers designed with an API that resembles as closely as possible a low level file I/O interface. A pipe may contain a system-defined maximum number of bytes at any given time, usually 4KB. As indicated in Figure 2.2, a process can send data by writing it into one end of the pipe and another can receive the data by reading the other end of the pipe. Information Flow Through a Pipe A pipe is represented in the kernel by a file descriptor, just like a file. A process that wants to create a pipe calls the kernel with a call of the following form: int thePipe[2]; pipe(thePipe); The kernel creates the pipe as a kernel FIFO data structure with two file identifiers. In this example code, thePipe[0] is a file pointer (an index into the process's open file table) to the read end of the pipe and thePipe[1] is file pointer to the write end of the pipe. For two or more processes to use pipes for IPC (interprocess communication), a common ancestor of the processes must create the pipe prior to creating the processes. Because the fork() command creates a child that contains a copy of the open file table (that is, the child has access to all of the files that the parent has already opened), the child inherits the pipes that the parent created. To use a pipe, it needs only to read and write the proper file descriptors. For example, suppose that a parent creates a pipe. It then can create a child and communicate with it by using a code fragment such as the following:
int pid; int thePipe[2]; pipe(thePipe); pid = fork(); // Parent if(pid > 0) { char message="Hello"; char messageLen=6; write(thePipe[1], message, messageLen); cout << "Parent sent: " << message << endl; } // Child else if (pid == 0) { char message[6]; int messageLen=6; read(thePipe[0], message, messageLen); cout << "Child received: " << message << endl; } Pipes enable processes to copy information from one address space to another by using the UNIX file model. The pipe read and write ends can be used in most system calls in the same way as a file descriptor. Further, the information written to and read from the pipe is a byte stream. UNIX pipes do not explicitly support messages, though two processes can establish their own protocol to provide structured messages. Also, library routines are available that can be used with a pipe to communicate via messages. A process that does not intend to use a pipe end should close so that end-of-file (EOF) conditions can be detected. A named pipe can be used to allow unrelated processes to communicate with each other. Typically in pipes, the children inherit the pipe ends as open file descriptors. In named pipes, a process obtains a pipe end by using a string that is analogous to a filename but that is associated with a pipe. This allows any set of processes to exchange information by using a public pipe whose end names are filenames. When a process uses a named pipe, the pipe is a system-wide resource, potentially accessible by any process. Just as files must be managed so that they are not inadvertently shared among many processes at one time, named pipes must be managed, by using low level file system commands.
// Launch the executable file with the specified parameters using // the execvp command and the argv array. } Determining the Command Name and the Parameter List A program might be run from your shell with the command: BobShell> ./main foo 100 Before calling execvp() you need to set up the argv array so that, argv[0] will point to the C-String “main”, argv[1] will point to “foo”, argv[2] will point to the string “100”, and argv[3] will be set to NULL to indicate the end of elements in the argv array. Your program then can interpret the first parameter (argv[1]) as, say, a filename, and the second parameter (argv[2]) as, say, an integer record count. The shell would simply treat the first word on the command line as a filename and the remaining words as strings. Finding the Full Pathname The user might have provided a full pathname as the command name word or only a relative pathname that is to be bound according to the value of the PATH environment variable. A name that begins with a "/" "./" or "../" is an absolute pathname that can be used to launch the execution. Otherwise, your program must search each directory in the list specified by the PATH environment variable to find the relative pathname. You can figure out if the file exists in a particular directory by trying to open the file. If the open fails, then the file does not exist. Launching the Command The final step in executing the command is to fork a child process to execute the specified command and then to cause the child to execute that command. The following code skeleton will accomplish this. // Child if (fork() == 0) { execvp(
int newstdout = open(outputFileName.c_str(),O_WRONLY|O_CREAT,S_IRWXU|S_IRWXG|S_IRWXO); To get command line pipes to work, re-read the Shell Pipes section carefully. Since a pipe is just like a file... there’s no reason why you couldn’t use I/O Redirection and pipes together! 1 - Have the parent create a pipe. 2 - Spawn a child. 3 - Have the parent redirect stdout to the write portion of the pipe. 4 - Have the parent execute the first command with excecvp(). 5 - Have the child redirect stdin to the read portion of the pipe. 6 - Have the child execute the second command with execvp(). 7 - The output from the parent command should flow to the child command via the pipe and i/o redirection you performed on the pipe. Watch out for (EOF) problems with pipes. I couldn't get the child process to terminate on an eof condition because the parent didn't close the read portion of the pipe. Make sure that for parent and child that you call the system call close() for any portion of a pipe you aren’t using. General Hints You should learn to use man pages to get info about important system calls. Sometimes the man page I wanted didn't come up when I typed man
... make a system call that fails cout << strerror(errno) << endl;