Shell Program - Write, compile, and run a C program for a custom-shell. Part 1.
ID: 664685 • Letter: S
Question
Shell Program - Write, compile, and run a C program for a custom-shell.
Part 1. Your shell will do the following, using system( ) to handle each command
1. Command prompt (for example, #, ##, %, %%, or of your choice).
2. Command “exit” or “quit” will exit (to terminate the program).
3. Command “list” will do what ls command does (using system)
Part 2. Command Parsing (and print its components) using system()
Your shell should be able to parse the command from user
1. One command with arguments and options.
For example, ls –la /home/richard
Command: la
Options: -la
Arguments: /home/richard
2. Two commands with 1 pipe.
For example, ls –la /home/richard
Command: la
Options: -la
Arguments: /home/richard
For example, ls | wc –l should be parsed and display
Command: ls
Pipe
Command: wc –l
3. Two commands with semicolon. For example, ls ; date
4. One command with IO redirection symbol (<, >, >>)
For example, ls < junk.txt > output.txt
Command: ls
File Redirection: <
File: junk.txt
File Redirection: >
File: output.txt
Part 3. Handle pipe (using fork, pipe, dup2, exec) with two commands.
Given a command from user, it forks a child process to execute the command while parent waits. When it is done, parent process wakes up and prints prompt for next command.
Syntax: command | command
Test line: ls -sF | grep /
Man pages: pipe, dup2.
** Note: If you cannot finish Part3, then continue Part4-6 with system().
Part 4. Handle background execution of command with "&" and a sequence commands with ";".
Test line: sleep 10 &
Test line: sleep 10; ls &
Part5. Signal processing (to handle Cntl+Z when command prompts) - SIGTSTP.
Terminate the shell by exit command "exit" or <CTRL->Z (^Z)
When a child process is running and the parent-process is waiting,
Cntl+Z will be handled by the parent’s signal handler to kill the child process.
Test Case: sleep 100 (and then press Cntl+Z) to kill the child process in sleep by the parent process.
And ps command to see whether the child process is killed (gone).
Part6 - Handle multiple commands connected with pipe.
For example, ls | grep ".c" | sort | tee list.txt | wc –l ; cat list.txt
Explanation / Answer
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
int main (int argc, char **argv)
{
while (1){
int childPid;
char * cmdLine;
printPrompt();
cmdLine= readCommandLine(); //or GNU readline("");
cmd = parseCommand(cmdLine);
record command in history list (GNU readline history ?)
if ( isBuiltInCommand(cmd)){
executeBuiltInCommand(cmd);
} else {
childPid = fork();
if (childPid == 0){
executeCommand(cmd); //calls execvp
} else {
if (isBackgroundJob(cmd)){
record in list of background jobs
} else {
waitpid (childPid);
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.