CS 170 Spring 05 Jshell Lab

Download Report

Transcript CS 170 Spring 05 Jshell Lab

CS 170 Spring 05
JShell Lab
What is a Shell?
• A shell is a command line interpreter; it
reads lines typed by the user and
interprets them as requests to execute
other programs.
Text editor
Calculator
Shell
Applications
Operating System
Machine (Hardware)
What is a Shell?
• Shell is a just another application; it has
– Input
– Does something (Processing)
– Output
Shell Input
• Commands typed at the prompt
• Needs to be parsed  parse.h
int parse(CMD **);
ex. error_code = parse(&commands);
int cmd_free(CMD *);
• Specail input -> exit or CTRL-D
CTRL-C: check signal(SIGINT, SIG_IGN)
Shell Input
int parse(CMD **);
• CMD is a pointer to a pointer of CMD struct.
/* command structure */
typedef struct command_struct {
struct command_struct * prevCmd;
struct command_struct * nextCmd;
char * file;
char ** argv;
char * in_redir;
char * out_redir;
int appending; /* flag, non-zero = append, zero = truncate */
int background; /* whether the line terminates with an & */
} CMD;
Shell input
• Very important:
– Check for the return value from parse(). You
have to handle errors and your shell must
report them.
– Before accessing any pointer, make sure it is
not NULL. Using a Null pointer will make your
code Seg fault.
Shell does something (Processing)
• Calling other applications.
Text editor
Calculator
Shell
exec
dup
fork
Applications
………………………..
Operating System
Machine (Hardware)
Shell does something (Processing)
• First: you need to fork a new process to run the
requested program by the user.
 use fork().
#include <stdio.h>
int main()
{
pid = fork();
printf("\nHello World\n”);
return 0;
}
How to tell which is which?
Use getpid() or fork-return value. 0? Yes: child, No:
Parent
Shell does something (Processing)
• Second: Shell asks the OS to run the userrequested program
Use execvp()
• Recall: difference between background
processes and foreground ones !!
• Execvp-ed cmd input/output should be
directed according to user request for that
cmd.
 Use dup2()
Shell output
• Your Prompt  Waiting for a new cmd.
General Remarks
• Use perror() to report the sys-calls error .
• Zombie processes.
 Use waitpid() or wait4()
• Test your code on CSIL machines
• Apply test codes.
• Provide a README file.
• Late assignments will receive a ZERO.
Submit what you have before the deadline.
Zombie processes check
• Command: ps –a
• Zombie will show as <defunct>
• Sample
Input:
[cs170@ella] [tmp2]: ./jshell
jshell: sleep 3 &
Output:
[cs170@ella] [tmp2]: ps -a
13858 pts/30 00:00:00 jshell
13896 pts/30 00:00:00 sleep <defunct>
13905 pts/1 00:00:00 ps
 Shouldn’t show up if waitpid
is correctly implemented.