C in a Unix environment Shell Program - Write, compile, and run a C program for
ID: 664228 • Letter: C
Question
C in a Unix environment
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.
2. Two commands with 1 pipe.
3. Two commands with semicolon. For example, ls ; date
4. One command with IO redirection symbol (<, >, >>)
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.
Part 4: Handle background execution of command with "&" and a sequence commands with ";".
Test line: sleep 10 &
Test line: sleep 10; ls &
Part 5: Signal processing (to handle Cntl+Z when command prompts) - SIGTSTP.
Terminate the shell by exit command "exit" or 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).
Part 6: 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>
int main(){
char ch[50];
strcpy(ch,"");
while((strcmp(ch,"exit")!=0)&&(strcmp(ch,"quit")!=0)){
printf(" # ");
scanf("%s",&ch);
if(strcmp(ch,"list")==0){
system("dir");
}else{
system(ch);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.