CSAPP:ShellLab
本文章就是在做
ShellLab
的源码以及对于内容的讲解,因为我自身比较菜因此其中的解释对于小白来说还是比较的友好的,其中思路代码等都来自于郭郭
建议读的顺序是sigint sigstop
->sigchld_hanlder
->waitfg
->builtin_command
->do_fg
->eval
做之前需要通读一遍csapp第八章的内容,尤其是waitpid
中的各种参数、sigprocmask
进行信号屏蔽的例子🌰要看懂,信号中断的处理。。。共勉,一起加油!
/*
* tsh - A tiny shell program with job control
*
* <Put your name and login ID here>
* Shao..
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
/* Misc manifest constants */
#define MAXLINE 1024 /* max line size */
#define MAXARGS 128 /* max args on a command line */
#define MAXJOBS 16 /* max jobs at any point in time */
#define MAXJID 1<<16 /* max job ID */
/* Job states */
#define UNDEF 0 /* undefined */
#define FG 1 /* running in foreground */
#define BG 2 /* running in background */
#define ST 3 /* stopped */
/*
* Jobs states: FG (foreground), BG (background), ST (stopped)
* Job state transitions and enabling actions:
* FG -> ST : ctrl-z
* ST -> FG : fg command
* ST -> BG : bg command
* BG -> FG : fg command
* At most 1 job can be in the FG state.
*/
/* Global variables */
extern char **environ; /* defined in libc */
char prompt[] = "tsh> "; /* command line prompt (DO NOT CHANGE) */
int verbose = 0; /* if true, print additional output */
int nextjid = 1; /* next job ID to allocate */
char sbuf[MAXLINE]; /* for composing sprintf messages */
struct job_t { /* The job struct */
pid_t pid; /* job PID */
int jid; /* job ID [1, 2, ...] */
int state; /* UNDEF, BG, FG, or ST */
char cmdline[MAXLINE]; /* command line */
};
struct job_t jobs[MAXJOBS]; /* The job list */
/* End global variables */
/* Function prototypes */
/* Here are the functions that you will implement */
void eval(char *cmdline);
int builtin_cmd(char **argv);
void do_bgfg(char **argv);
void waitfg(pid_t pid);
void sigchld_handler(int sig);
void sigtstp_handler(int sig);
void sigint_handler(int sig);
/* Here are helper routines that we've provided for you */
int parseline(const char *cmdline, char **argv);
void sigquit_handler(int sig);
void clearjob(struct job_t *job);
void initjobs(struct job_t *jobs);
int maxjid(struct job_t *jobs);
int addjob(struct job_t *jobs, pid_t pid, int state, char *cmdline);
int deletejob(struct job_t *jobs, pid_t pid);
pid_t fgpid(struct job_t *jobs);
struct job_t *getjobpid(struct job_t *jobs, pid_t pid);
struct job_t *getjobjid(struct job_t *jobs, int jid);
int pid2jid(pid_t pid);
void listjobs(struct job_t *jobs);
void usage(void);
void unix_error(char *msg);
void app_error(char *msg);
typedef void handler_t(int);
handler_t *Signal(int signum, handler_t *handler);
/*
* main - The shell's main routine
*/
int main(int argc, char **argv)
{
char c;
char cmdline[MAXLINE];
int emit_prompt = 1; /* emit prompt (default) */
/* Redirect stderr to stdout (so that driver will get all output
* on the pipe connected to stdout) */
dup2(1, 2);
/* Parse the command line */
while ((c = getopt(argc, argv, "hvp")) != EOF) {
switch (c) {
case 'h': /* print help message */
usage();
break;
case 'v': /* emit additional diagnostic info */
verbose = 1;
break;
case 'p': /* don't print a prompt */
emit_prompt = 0; /* handy for automatic testing */
break;
default:
usage();
}
}
/* Install the signal handlers */
/* These are the ones you will need to implement */
Signal(SIGINT, sigint_handler); /* ctrl-c */
Signal(SIGTSTP, sigtstp_handler); /* ctrl-z */
Signal(SIGCHLD, sigchld_handler); /* Terminated or stopped child */
/* This one provides a clean way to kill the shell */
Signal(SIGQUIT, sigquit_handler);
/* Initialize the job list */
initjobs(jobs);
/* Execute the shell's read/eval loop */
while (1) {
/* Read command line */
if (emit_prompt) {
printf("%s", prompt);
fflush(stdout);
}
if ((fgets(cmdline, MAXLINE, stdin) == NULL) && ferror(stdin))
app_error("fgets error");
if (feof(stdin)) { /* End of file (ctrl-d) */
fflush(stdout);
exit(0);
}
/* Evaluate the command line */
eval(cmdline); /*parse cmdlines and evaluate the argvs*/
fflush(stdout); /*flush the buf area*/
fflush(stdout);
}
exit(0); /* control never reaches here */
}
/*
* eval - Evaluate the command line that the user has just typed in
*
* If the user has requested a built-in command (quit, jobs, bg or fg)
* then execute it immediately. Otherwise, fork a child process and
* run the job in the context of the child. If the job is running in
* the foreground, wait for it to terminate and then return. Note:
* each child process must have a unique process group ID so that our
* background children don't receive SIGINT (SIGTSTP) from the kernel
* when we type ctrl-c (ctrl-z) at the keyboard.
*/
void eval(char *cmdline)
{
//在原书中P543中,我们通过mask解决了子进程早于父进程执行从而出错的情况
//我们在子进程中解掉block 因为子进程同样继承了父进程的mask,但是如果子进程再fork的话,它的子进程不应该被block,因此子进程中应该解除block
char * argv[MAXARGS];
int bg; //judge if is bg
pid_t pid;
sigset_t mask;
bg = parseline(cmdline, argv);
if (!builtin_cmd(argv)) {
//掩码不在函数外面加是因为:我们上面函数如果是系统调用就直接执行就好了,不需要进行阻塞
//函数能执行到这里就代表不是系统调用了,那么我们就是应该进行阻塞,因为存在有sigchld_handler 在外面
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD); //阻塞回收子进程
sigprocmask(SIG_BLOCK, &mask, NULL);
if ((pid = fork()) < 0)
unix_error("forking error");
else if (pid == 0) { //shell 需要创建一个新的子进程执行我们锁输入的命令
sigprocmask(SIG_UNBLOCK, &mask, NULL); //上面讲述的,解除掉子进程中的block
/*
* 下面新创建一个进程组的原因就是:
* 如果不创建的话,我们的shell(父进程)同command(子进程)是属于一个进程组的
* 如果我们执行了SIGINT | SIGSTOP的话,shell 和 command都没了
* 这时候如果我们ctrl + c 的话,只会去处理前台的进程
*/
setpgid(0, 0); //创建新的进程组(进程组的ID就是目前进程的ID),不然如果前台有一个kill就将父进程和子进程都杀掉了
if (execvp(argv[0], argv) < 0) { //执行文件 argv[0], 后面的就作为参数进行传递
printf("%s command not found\n", argv[0]);
exit(1);
}
}else { //parent process add job
if (!bg) {
addjob(jobs, pid, FG, cmdline);
}else {
addjob(jobs, pid, BG, cmdline);
}
sigprocmask(SIG_UNBLOCK, &mask, NULL);
//上面的都是被mask进行包住了,比如说更改共享变量的时候我们就相当于上了一把锁一样
if (!bg) {
waitfg(pid);
}else {
printf("[%d] (%d) %s", pid2jid(pid), pid, cmdline);
}
}
}
}
/*
* parseline - Parse the command line and build the argv array.
*
* Characters enclosed in single quotes are treated as a single
* argument. Return true if the user has requested a BG job, false if
* the user has requested a FG job.
*/
int parseline(const char *cmdline, char **argv)
{
static char array[MAXLINE]; /* holds local copy of command line */
char *buf = array; /* ptr that traverses command line */
char *delim; /* points to first space delimiter */
int argc; /* number of args */
int bg; /* background job? */
strcpy(buf, cmdline);
buf[strlen(buf)-1] = ' '; /* replace trailing '\n' with space */
while (*buf && (*buf == ' ')) /* ignore leading spaces */
buf++;
/* Build the argv list */
argc = 0;
if (*buf == '\'') {
buf++;
delim = strchr(buf, '\'');
}
else {
delim = strchr(buf, ' ');
}
while (delim) {
argv[argc++] = buf;
*delim = '\0';
buf = delim + 1;
while (*buf && (*buf == ' ')) /* ignore spaces */
buf++;
if (*buf == '\'') {
buf++;
delim = strchr(buf, '\'');
}
else {
delim = strchr(buf, ' ');
}
}
argv[argc] = NULL;
if (argc == 0) /* ignore blank line */
return 1;
/* should the job run in the background? */
if ((bg = (*argv[argc-1] == '&')) != 0) {
argv[--argc] = NULL;
}
return bg;
}
/*
* builtin_cmd - If the user has typed a built-in command then execute
* it immediately.
*/
int builtin_cmd(char **argv) //判断是否是内置的函数quit,bg,&,jobs, 是的话进行处理 & return 1
{
if (strcmp(argv[0], "quit") == 0) {
exit(0);
//return 1;
}else if (strcmp(argv[0],"jobs") == 0) {
//call function : listjobs
listjobs(jobs);
return 1;
}else if (strcmp(argv[0], "&") == 0) {
//试过了,只输入&的话 啥也不是
//bash: syntax error near unexpected token `&'
return 1;
}else if (strcmp(argv[0], "bg") == 0 | strcmp(argv[0], "fg") == 0 ) {
//看看下一个函数就是do_bgfg
do_bgfg(argv);
return 1;
}
return 0; /* not a builtin command */
}
/*
* do_bgfg - Execute the builtin bg and fg commands
*/
void do_bgfg(char **argv)
{
struct job_t * job;
pid_t pid;
int jid;
int status;
char * tmp;
tmp = argv[1];
if (tmp == NULL) {
printf("%s command requires PID or %%jobid argument\n", argv[0]);
return ;
}
if (tmp[0] == '%') {
//input is a jobid
jid = atoi(tmp + 1);
job = getjobjid(jobs, jid); //通过jid找到那个需要执行的job
if (job == NULL) {
printf("%s: No such job\n", tmp);
return ;
}else {
pid = job -> pid;
}
}else if (isdigit(atoi(&tmp))) { //只是数字的话那么就是输入的是进程ID了
pid = atoi(tmp);
job = getjobpid(jobs, pid);
if (job == NULL) {
printf("(%d): No such process\n", pid);
return ;
}
}else {
printf("%s: argument must be a PID or %%jobid\n", argv[0]);
}
//现在拿到了需要执行的job
kill(pid, SIGCONT); //不是kill,是继续执行的意思,本来就工作就继续,没有工作就开始工作
//已经处理完job了,下面看一下前台后台的处理
if (strcmp(argv[0], "fg") == 0) {
job -> state = FG; //将任务的状态写成是FG:前台
waitfg(job -> pid); //在这个前台任务完成之前,都是一直block的
/*
* To小呆瓜:
* 你可能有疑问说:为什么我们能够直接将这个程序作为前台程序呢?要是前台程序本身没退出怎么办?
* 答:因为你执行这个命令行就是输入了command XXXXX,也就是唯一的前台程序就是这个输入而已,按下回车后你这个程序就成为前台程序了
* 别问我为什么知道这个问题,,,,
*/
}else {
printf("[%d] (%d) %s", job -> jid, job -> pid, job -> cmdline);
job -> state = BG;
}
}
/*
* waitfg - Block until process pid is no longer the foreground process
*/
void waitfg(pid_t pid)
{
//就是如果前台的程序是pid的话我们就一直等待着
//首先判断一下给的pid这个任务是否是存在的
struct jobs * job = getjobpid(jobs, pid);
if (job == NULL) return ; //根本就没有这个程序,直接退出
/*
* 一种实现:waipid(前台程序),我们就等待前台进程的结束、这样不就行了吗?
*
* 不好的原因:我们写了一个sigchld_handler()的函数(当前台程序结束会被这个自定义处理信号量的函数收回),在前台进程结束的时候也是需要获得pid的
* 所以上面两个就会出现争夺pid的情况😂
* 为了避免datarace、我们就用自旋spin的方式好了
*/
while(fgpid(jobs) == pid) { //spin ..... until pid is not foreground
}
}
/*****************
* Signal handlers
*****************/
/*
* sigchld_handler - The kernel sends a SIGCHLD to the shell whenever
* a child job terminates (becomes a zombie), or stops because it
* received a SIGSTOP or SIGTSTP signal. The handler reaps all
* available zombie children, but doesn't wait for any other
* currently running children to terminate.
*/
//为什么处理信号的时候不需要进行block呢?
//因为信号是不会进行计数的,如果本身存在了一个信号的话,你来多少信号我都只知道:现在存在一个信号执行,并不关心有多少个
//第二个同类型的信号是不会打断上一个正在处理的信号的:-)
void sigchld_handler(int sig)
{
/*
* 它不像waitpid一样等待子进程的终止,如果没有终止的子进程就直接退出(返回0), 如果有的话就处理后返回(pid)
*/
int olderrno = errno;
pid_t pid;
int status;
/*
* 我们因为是不能够被阻塞的(也就是不会等待)& 需要处理stop的程序
* 因此我们的option就是需要选择下面两种的配合
*/
while (waitpid(-1, &status, WNOHANG | WUNTRACED) > 0) {
if (WIFEXITED(status)) {
//通过正常的exit进行的退出
deletejob(jobs, pid);
}else if (WIFSIGNALED(status)) {
//通过被信号杀掉
int jid = pid2jid(pid);
printf("Job [%d] (%d) terminated by signal %d\n", jid, pid, WTERMSIG(status)); //返回导致被信号杀掉的pid,这两个函数是搭配使用的
deletejob(jobs, pid);
}else {
//子进程已经是stop了
struct job_t * job = getjobpid(jobs, pid); //获得指向已经退出子进程的结构体的指针,我们更改它的状态
job -> state = ST; //修改进程的状态为stop
int jid = pid2jid(pid);
printf("Job [%d] (%d) Stopped by signal %d\n", jid, pid, WSTOPSIG(status));
}
}
errno = olderrno;
}
/*
* sigint_handler - The kernel sends a SIGINT to the shell whenver the
* user types ctrl-c at the keyboard. Catch it and send it along
* to the foreground job.
*/
void sigint_handler(int sig)
{
/*
* 捕获ctrl + c 信号,打印这句到前台程序中,然后退出
* 1.找到当前运行的前台程序
* 2.kill掉程序,需要kill掉的是一个进程组(用-pid就是消灭进程组)
* 3.打印
*/
pid_t pid = fgpid(jobs);
if (pid == 0) //前台没有进程,直接return
return;
kill(-pid, sig);
}
/*
* sigtstp_handler - The kernel sends a SIGTSTP to the shell whenever
* the user types ctrl-z at the keyboard. Catch it and suspend the
* foreground job by sending it a SIGTSTP.
*/
void sigtstp_handler(int sig)
{
/*
* 同上,stop也是,我们至少前台程序是不能够留下的
*/
pid_t pid = fgpid(jobs);
if (pid == 0) //前台没有进程,直接return
return;
kill(-pid, sig);
}
/*********************
* End signal handlers
*********************/
/***********************************************
* Helper routines that manipulate the job list
**********************************************/
/* clearjob - Clear the entries in a job struct */
void clearjob(struct job_t *job) {
job->pid = 0;
job->jid = 0;
job->state = UNDEF;
job->cmdline[0] = '\0';
}
/* initjobs - Initialize the job list */
void initjobs(struct job_t *jobs) {
int i;
for (i = 0; i < MAXJOBS; i++)
clearjob(&jobs[i]);
}
/* maxjid - Returns largest allocated job ID */
int maxjid(struct job_t *jobs)
{
int i, max=0;
for (i = 0; i < MAXJOBS; i++)
if (jobs[i].jid > max)
max = jobs[i].jid;
return max;
}
/* addjob - Add a job to the job list */
int addjob(struct job_t *jobs, pid_t pid, int state, char *cmdline)
{
int i;
if (pid < 1)
return 0;
for (i = 0; i < MAXJOBS; i++) {
if (jobs[i].pid == 0) { //如果这个存放job的结构还没有被占用,就分配给当前的进程
jobs[i].pid = pid;
jobs[i].state = state;
jobs[i].jid = nextjid++; //golbal argument : nextjid 是下一个可以分配的jobid, 如果用完了就置为1
if (nextjid > MAXJOBS)
nextjid = 1;
strcpy(jobs[i].cmdline, cmdline);
if(verbose){ //是否打印其他的信息
printf("Added job [%d] %d %s\n", jobs[i].jid, jobs[i].pid, jobs[i].cmdline);
}
return 1;
}
}
printf("Tried to create too many jobs\n");
return 0;
}
/* deletejob - Delete a job whose PID=pid from the job list */
int deletejob(struct job_t *jobs, pid_t pid)
{
int i;
if (pid < 1)
return 0;
for (i = 0; i < MAXJOBS; i++) {
if (jobs[i].pid == pid) {
clearjob(&jobs[i]);
nextjid = maxjid(jobs)+1;
return 1;
}
}
return 0;
}
/* fgpid - Return PID of current foreground job, 0 if no such job */
pid_t fgpid(struct job_t *jobs) { //因为前台任务只有一个,因此返回的只有一个值
int i;
for (i = 0; i < MAXJOBS; i++)
if (jobs[i].state == FG)
return jobs[i].pid;
return 0;
}
/* getjobpid - Find a job (by PID) on the job list */
struct job_t *getjobpid(struct job_t *jobs, pid_t pid) { //通过pid找到任务列表中的任务(返回的是结构体指针)
int i;
if (pid < 1)
return NULL;
for (i = 0; i < MAXJOBS; i++)
if (jobs[i].pid == pid)
return &jobs[i];
return NULL;
}
/* getjobjid - Find a job (by JID) on the job list */
struct job_t *getjobjid(struct job_t *jobs, int jid) //通过jid找到任务,返回的是任务的结构体指针
{
int i;
if (jid < 1)
return NULL;
for (i = 0; i < MAXJOBS; i++)
if (jobs[i].jid == jid)
return &jobs[i];
return NULL;
}
/* pid2jid - Map process ID to job ID */
int pid2jid(pid_t pid) //通过pid找到jobid
{
int i;
if (pid < 1)
return 0;
for (i = 0; i < MAXJOBS; i++)
if (jobs[i].pid == pid) {
return jobs[i].jid;
}
return 0;
}
/* listjobs - Print the job list */
void listjobs(struct job_t *jobs)
{
int i;
for (i = 0; i < MAXJOBS; i++) {
if (jobs[i].pid != 0) {
printf("[%d] (%d) ", jobs[i].jid, jobs[i].pid);
switch (jobs[i].state) {
case BG:
printf("Running ");
break;
case FG:
printf("Foreground ");
break;
case ST:
printf("Stopped ");
break;
default:
printf("listjobs: Internal error: job[%d].state=%d ",
i, jobs[i].state);
}
printf("%s", jobs[i].cmdline);
}
}
}
/******************************
* end job list helper routines
******************************/
/***********************
* Other helper routines
***********************/
/*
* usage - print a help message
*/
void usage(void)
{
printf("Usage: shell [-hvp]\n");
printf(" -h print this message\n");
printf(" -v print additional diagnostic information\n");
printf(" -p do not emit a command prompt\n");
exit(1);
}
/*
* unix_error - unix-style error routine
*/
void unix_error(char *msg)
{
fprintf(stdout, "%s: %s\n", msg, strerror(errno));
exit(1);
}
/*
* app_error - application-style error routine
*/
void app_error(char *msg)
{
fprintf(stdout, "%s\n", msg);
exit(1);
}
/*
* Signal - wrapper for the sigaction function
*/
handler_t *Signal(int signum, handler_t *handler)
{
struct sigaction action, old_action;
action.sa_handler = handler;
sigemptyset(&action.sa_mask); /* block sigs of type being handled */
action.sa_flags = SA_RESTART; /* restart syscalls if possible */
if (sigaction(signum, &action, &old_action) < 0)
unix_error("Signal error");
return (old_action.sa_handler);
}
/*
* sigquit_handler - The driver program can gracefully terminate the
* child shell by sending it a SIGQUIT signal.
*/
void sigquit_handler(int sig)
{
printf("Terminating after receipt of SIGQUIT signal\n");
exit(1);
}