TinyShell(CSAPP实验)

鼠扑  金牌会员 | 2022-12-5 11:59:07 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 577|帖子 577|积分 1731

简介

CSAPP实验介绍

学生实现他们自己的带有作业控制的Unix Shell程序,包括Ctrl + C和Ctrl + Z按键,fg,bg,和 jobs命令。这是学生第一次接触并发,并且让他们对Unix的进程控制、信号和信号处理有清晰的了解。
什么是Shell?

​                        Shell就是用户与操作系统内核之间的接口,起着协调用户与系统的一致性和在用户与系统之间进行交互的作用。
​                        Shell最重要的功能是命令解释,从这种意义上说,Shell是一个命令解释器。
​                        Linux系统上的所有可执行文件都可以作为Shell命令来执行。当用户提交了一个命令后,Shell首先判断它是否为内置命令,如果是就通过Shell内部的解释器将其解释为系统功能调用并转交给内核执行;若是外部命令或实用程序就试图在硬盘中查找该命令并将其调入内存,再将其解释为系统功能调用并转交给内核执行。在查找该命令时分为两种情况:
(1)用户给出了命令的路径,Shell就沿着用户给出的路径进行查找,若找到则调入内存,若没找到则输出提示信息;
(2)用户没有给出命令的路径,Shell就在环境变量Path所制定的路径中依次进行查找,若找到则调入内存,若没找到则输出提示信息。
关于本次实验

本次实验需要我们熟读CSAPP第八章异常控制流
需要设计和实现的函数:

  • eval 函数:解析命令行。
Evaluate the command line that the user has just typed in.


  • builtin_cmd:判断是否为内置 shell 命令
If the user has typed a built-in command then execute it immediately.


  • do_bgfg:实现内置命令bgfg
Execute the builtin bg and fg commands.


  • waitfg:等待前台作业完成。
Block until process pid is no longer the foreground process


  • sigchld_handler:捕获SIGCHLD信号。
  • sigint_handler:捕获SIGINT信号。
  • sigtstp_handler:捕获SIGTSTP信号。
TinyShell辅助函数:
  1. /* Here are helper routines that we've provided for you */
  2. int parseline(const char *cmdline, char **argv); //解析命令行参数
  3. void sigquit_handler(int sig);//退出的处理函数
  4. /*jobs是全局变量,存储每一个进程的信息。*/
  5. /*jid为job编号ID,pid为进程ID*/
  6. void clearjob(struct job_t *job);//清除所有工作
  7. void initjobs(struct job_t *jobs);//初始化工作结构体
  8. int maxjid(struct job_t *jobs); //返回jobs中jid的最大值
  9. int addjob(struct job_t *jobs, pid_t pid, int state, char *cmdline);//添加job
  10. int deletejob(struct job_t *jobs, pid_t pid); //删除job
  11. pid_t fgpid(struct job_t *jobs);//返回前台运行job的pid
  12. struct job_t *getjobpid(struct job_t *jobs, pid_t pid);//返回对应pid的job
  13. struct job_t *getjobjid(struct job_t *jobs, int jid); //返回jid对应的job
  14. int pid2jid(pid_t pid); //pid转jid
  15. void listjobs(struct job_t *jobs);//遍历
  16. void usage(void);//帮助信息
  17. void unix_error(char *msg);//报错unix-style error routine
  18. void app_error(char *msg);//报错application-style error routine
  19. typedef void handler_t(int);
  20. handler_t *Signal(int signum, handler_t *handler);//信号设置
复制代码
实验要求


  • tsh的提示符:tsh>
  • 用户输入的命令行应该包括一个名字、0或多个参数,并用一个或多个空格分隔。
  • 如果名字是内置命令,tsh立即处理并等待用户输入下一个命令行。否则,假定这个名字是一个可执行文件的路径,tsh在初始子进程的上下文中加载和运行它。
  • tsh不需要支持管(|)或I/O重定向()。
  • 键入ctrl-cctrl-z)应该导致SIGINTSIGTSTP)信号被发送到当前的前台作业,及其该作业的子孙作业(例如,它创建的任何子进程)。如果没有前台工作,那么信号应该没有效果。
  • 如果命令行以&结尾,则tsh在后台运行该作业;否则,在前台运行该作业
  • 可以用进程ID(PID)tsh赋予的正整数作业IDjob IDJID)标识一个作业。JID用前缀%,例如%5标识作业ID5的作业,5表示PID5的作业。
  • 已经提供了处理作业列表所需的所有函数
  • tsh支持以下内置命令:

    • quit:终止tsh程序
    • jobs:列出所有后台job
    • bg:后台运行程序
    • fg:前台运行程序

回顾

fork

pid_t fork(void)
在函数调用处创建子进程。
父进程函数返回子进程的PID
子进程函数返回0
waitpid

一个进程可以通过waitpid函数来等待它的子进程终止或者停止。
pid_t waitpid(pid_t pid, int *statusp, int options);
pid:判定等待集合的成员


  • pid > 0时,waitpid等待进程ID为pid的进程;
  • pid = -1时,waitpid等待所有它的子进程。
options:修改默认行为

options中有如下选项:

  • WNOHANG:若当前没有等待集合中的子进程终止,则立即返回0
  • WUNTRACED:等待直到某个等待集合中的子进程停止或返回,并返回这个子进程的pid。
  • WCONTINUED:等待直到某个等待集合中的子进程重新开始执行或终止。
  • 组合WNOHANG | WUNTRACED:立即返回,如果等待集合中的子进程都没有被停止或终止,则返回0。如果有,则返回PID。
statusp:检查已回收子进程的退出状态

如果statusp参数非空,那么waitpid就会在status中放入关于导致返回的子进程的状态信息,status是statusp指向的值。

  • WIFEXITED(status):如果子进程通过调用exit或者返回(return)正常终止,就返回真。
  • ········
kill函数

int kill(pid_t pid, int signo);

  • pid > 0,信号发送给pid进程;
  • pid == 0,把信号发送给本进程(自己)所在的进程组中所有进程,不包括系统进程;
  • pid < 0,把信号发送给组id 为 -pid 的进程组中所有进程;
  • pid == -1,把信号发送给所有进程,除系统进程外(有些进程不接受9和19号信号)
安全的信号处理

目的

让信号处理程序和主程序它们可以安全地,无错误地,按照我们预期地并发地运行。
方法


  • 处理程序尽可能简单。
  • 在处理程序只调用异步信号安全的函数。

    • 可重入的(只访问局部变量)。
    • 不能被信号处理程序中断。

  • 保存和恢复errno。避免干扰其他依赖于errno的部分。解决方法是用局部变量存储,再恢复。
  1. void Example(int sig)
  2. {
  3.         int olderrno = errno;
  4.     /*
  5.     this is your code
  6.     */
  7.     errno = olderrno;
  8. }
复制代码

  • 阻塞所有信号,保护对共享全局变量数据结构的访问。
  • volatile声明全局变量。
  • sig_atomic_t声明标志。
例:在添加job时,阻塞信号,因为jobs是全局变量。
This is a little tricky. Block SIGCHLD, SIGINT, and SIGTSTP signals until we can add the job to the job list. This eliminates some nasty races between adding a job to the job list and the arrival of SIGCHLD, SIGINT, and SIGTSTP signals.
注意


  • 不可以用信号来对其他进制中发生的事件计数。
  • 使用原子(atomic)函数如sigsuspend函数消除潜在的竞争并提高效率。
实验

eval

要点分析:

  • 创建子进程前需要阻塞信号,防止竞争。
  • 将子进程加入到jobs后,需要恢复,即解除阻塞。
  • 创建子进程时,为子进程创建一个新的进程组。
  1. /*
  2. * eval - Evaluate the command line that the user has just typed in
  3. *
  4. * If the user has requested a built-in command (quit, jobs, bg or fg)
  5. * then execute it immediately. Otherwise, fork a child process and
  6. * run the job in the context of the child. If the job is running in
  7. * the foreground, wait for it to terminate and then return.  Note:
  8. * each child process must have a unique process group ID so that our
  9. * background children don't receive SIGINT (SIGTSTP) from the kernel
  10. * when we type ctrl-c (ctrl-z) at the keyboard.  
  11. */
  12. void eval(char *cmdline)
  13. {
  14.     /* $begin handout */
  15.     char *argv[MAXARGS]; /* argv for execve() */
  16.     int bg;              /* should the job run in bg or fg? */
  17.     pid_t pid;           /* process id */
  18.     sigset_t mask;       /* signal mask */
  19.     /* Parse command line */
  20.     bg = parseline(cmdline, argv);
  21.     if (argv[0] == NULL)  
  22.                 return;   /* ignore empty lines */
  23.     if (!builtin_cmd(argv)) {
  24.                         /*
  25.                 * This is a little tricky. Block SIGCHLD, SIGINT, and SIGTSTP
  26.                 * signals until we can add the job to the job list. This
  27.                 * eliminates some nasty races between adding a job to the job
  28.                 * list and the arrival of SIGCHLD, SIGINT, and SIGTSTP signals.  
  29.                 */
  30.                 if (sigemptyset(&mask) < 0)
  31.                         unix_error("sigemptyset error");
  32.                 if (sigaddset(&mask, SIGCHLD))
  33.                         unix_error("sigaddset error");
  34.                 if (sigaddset(&mask, SIGINT))
  35.                         unix_error("sigaddset error");
  36.                 if (sigaddset(&mask, SIGTSTP))
  37.                         unix_error("sigaddset error");
  38.                 if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0)
  39.                         unix_error("sigprocmask error");
  40.                 /* Create a child process */
  41.                 if ((pid = fork()) < 0)
  42.                         unix_error("fork error");
  43.                
  44.                 /*
  45.                 * Child  process
  46.                 */
  47.                 if (pid == 0) {
  48.                         /* Child unblocks signals */
  49.                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
  50.                         /* Each new job must get a new process group ID
  51.                         so that the kernel doesn't send ctrl-c and ctrl-z
  52.                         signals to all of the shell's jobs */
  53.                         if (setpgid(0, 0) < 0)
  54.                                 unix_error("setpgid error");
  55.                         /* Now load and run the program in the new job */
  56.                         if (execve(argv[0], argv, environ) < 0) {
  57.                                 printf("%s: Command not found\n", argv[0]);
  58.                                 exit(0);
  59.                         }
  60.         }
  61.         /*
  62.          * Parent process
  63.          */
  64.         /* Parent adds the job, and then unblocks signals so that
  65.            the signals handlers can run again */
  66.         addjob(jobs, pid, (bg == 1 ? BG : FG), cmdline);
  67.         sigprocmask(SIG_UNBLOCK, &mask, NULL);
  68.         if (!bg)
  69.             waitfg(pid);
  70.         else
  71.             printf("[%d] (%d) %s", pid2jid(pid), pid, cmdline);
  72.     }
  73.     /* $end handout */
  74.     return;
  75. }
复制代码
builtin_cmd

要点分析:
调用listjobs时,属于访问全局变量,需要阻塞和解除阻塞。
  1. /*
  2. * builtin_cmd - If the user has typed a built-in command then execute
  3. *    it immediately.  
  4. */
  5. int builtin_cmd(char **argv)
  6. {
  7.         if(*argv == NULL)
  8.         {
  9.                 return 0;
  10.         }
  11.         sigset_t mask, prev_mask;
  12.         if(sigfillset(&mask))
  13.         {
  14.                 unix_error("sigfillset error!");
  15.         }
  16.         if(! strcmp(argv[0], "quit"))
  17.         {
  18.                 if(sigprocmask(SIG_SETMASK, &mask, &prev_mask))//访问全局变量需要阻塞
  19.                 {
  20.                         unix_error("sigprocmask error!");
  21.                 }
  22.                 int i;
  23.                 for(i = 0; i < MAXJOBS; i ++ )//退出时终止所有所有的子进程
  24.                 {
  25.                         if(jobs[i].pid)
  26.                         {
  27.                                 kill(- jobs[i].pid, SIGINT);
  28.                         }
  29.                 }
  30.                 if(sigprocmask(SIG_SETMASK, &prev_mask, NULL))
  31.                 {
  32.                         unix_error("sigprocmask error!");
  33.                 }
  34.                 exit(0);//Shell exit
  35.         }else if(! strcmp(argv[0], "jobs"))
  36.         {
  37.                 if(sigprocmask(SIG_SETMASK, &mask, &prev_mask))//同理,访问全局变量
  38.                 {
  39.                         unix_error("sigprocmask error!");
  40.                 }
  41.                 listjobs(jobs);//遍历
  42.                 if(sigprocmask(SIG_SETMASK, &prev_mask, NULL))
  43.                 {
  44.                         unix_error("sigprocmask error!");
  45.                 }
  46.                 return 1;
  47.         }else if(! strcmp(argv[0], "&"))
  48.         {
  49.                 return 1;// &也是内置命令,需要返回1
  50.         }else if(! strcmp(argv[0], "fg") || ! strcmp(argv[0], "bg"))
  51.         {
  52.                 do_bgfg(argv);
  53.                 return 1;
  54.         }
  55.     return 0;     /* not a builtin command */
  56. }
复制代码
do_bgfg

要点分析:

  • 需要保证参数正确,即将不正确的情况排除。
  • 区别jid和pid。
  1. /*
  2. * do_bgfg - Execute the builtin bg and fg commands
  3. */
  4. void do_bgfg(char **argv)
  5. {
  6.     /* $begin handout */
  7.     struct job_t *jobp = NULL;
  8.    
  9.     /* Ignore command if no argument */
  10.     if (argv[1] == NULL) {
  11.                 printf("%s command requires PID or %%jobid argument\n", argv[0]);
  12.                 return;
  13.     }
  14.    
  15.     /* Parse the required PID or %JID arg */
  16.     if (isdigit(argv[1][0])) {
  17.                 pid_t pid = atoi(argv[1]);
  18.                 if (!(jobp = getjobpid(jobs, pid))) {
  19.                     printf("(%d): No such process\n", pid);
  20.                     return;
  21.                 }
  22.     }
  23.     else if (argv[1][0] == '%') {
  24.                 int jid = atoi(&argv[1][1]);
  25.                 if (!(jobp = getjobjid(jobs, jid))) {
  26.                     printf("%s: No such job\n", argv[1]);
  27.                     return;
  28.                 }
  29.     }            
  30.     else {
  31.                 printf("%s: argument must be a PID or %%jobid\n", argv[0]);
  32.                 return;
  33.     }
  34.     /* bg command */
  35.     if (!strcmp(argv[0], "bg")) {
  36.                 if (kill(-(jobp->pid), SIGCONT) < 0)
  37.                     unix_error("kill (bg) error");
  38.                 jobp->state = BG;
  39.                 printf("[%d] (%d) %s", jobp->jid, jobp->pid, jobp->cmdline);
  40.     }
  41.     /* fg command */
  42.     else if (!strcmp(argv[0], "fg")) {
  43.                 if (kill(-(jobp->pid), SIGCONT) < 0)
  44.                             unix_error("kill (fg) error");
  45.                 jobp->state = FG;
  46.                 waitfg(jobp->pid);
  47.     }
  48.     else {
  49.                 printf("do_bgfg: Internal error\n");
  50.                 exit(0);
  51.     }
  52.     /* $end handout */
  53.     return;
  54. }
复制代码
waitfg

要点分析:

  • 在等待的循环不使用可能会无限休眠的pause,也不使用太慢的sleep。
  • 在等待的循环中使用sigsuspend函数,因为它是原子的。
  • 在等待前,需阻塞chld信号。
  1. /*
  2. * waitfg - Block until process pid is no longer the foreground process
  3. */
  4. void waitfg(pid_t pid)
  5. {
  6.         sigset_t mask, prev_mask;
  7.         if(sigemptyset(&mask))
  8.         {
  9.                 unix_error("sigempty error!");
  10.         }
  11.         if(sigaddset(&mask, SIGCHLD))
  12.         {
  13.                 unix_error("sigaddset error!");
  14.         }
  15.         if(sigprocmask(SIG_SETMASK, &mask, &prev_mask))//访问jobs先阻塞chld信号
  16.         {
  17.                 unix_error("sigprocmask error!");
  18.         }
  19.         while(fgpid(jobs) == pid)
  20.         {
  21.                 sigsuspend(&prev_mask);//消除竞争
  22.         }
  23.         //
  24.         if(sigprocmask(SIG_SETMASK, &prev_mask, NULL))
  25.         {
  26.                 unix_error("sigprocmask error!");
  27.         }
  28.        
  29.     return;
  30. }
复制代码
sigchld_handler

要点分析:

  • 删除作业信息时,属于访问全局变量,需要阻塞全部信号。
  • 保存恢复errno。
  1. /*
  2. * sigchld_handler - The kernel sends a SIGCHLD to the shell whenever
  3. *     a child job terminates (becomes a zombie), or stops because it
  4. *     received a SIGSTOP or SIGTSTP signal. The handler reaps all
  5. *     available zombie children, but doesn't wait for any other
  6. *     currently running children to terminate.  
  7. */
  8. void sigchld_handler(int sig)
  9. {
  10.         int olderrno = errno;
  11.        
  12.         pid_t pid;
  13.         int status;
  14.         sigset_t mask, prev_mask;
  15.         if(sigfillset(&mask))
  16.         {
  17.                 unix_error("sigfillset error!");
  18.         }
  19.        
  20.         while((pid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0)
  21.         {
  22.                 if(sigprocmask(SIG_SETMASK, &mask, &prev_mask))//访问全局变量前阻塞所有信号
  23.                 {
  24.                         unix_error("sigprocmask error!");
  25.                 }
  26.                 struct job_t *temp = getjobpid(jobs, pid);
  27.                 if(WIFEXITED(status))//正常结束
  28.                 {
  29.                         deletejob(jobs, pid);
  30.                 }else if(WIFSIGNALED(status))//被未捕获的信号终止
  31.                 {
  32.                        
  33.                         int jid = pid2jid(pid);
  34.                         printf("Job [%d] (%d) terminated by signal %d\n", jid, pid, WTERMSIG(status));
  35.                         deletejob(jobs, pid);
  36.                 }else if(WIFSTOPPED(status))//停止的信号
  37.                 {
  38.                         temp->state = ST;
  39.                         int jid = pid2jid(pid);
  40.                         printf("Job [%d] (%d) stopped by signal %d\n", jid, pid, WSTOPSIG(status));
  41.                 }
  42.                 fflush(stdout);//之前printf输出,所以刷新
  43.                 if(sigprocmask(SIG_SETMASK, &prev_mask, NULL))
  44.                 {
  45.                         unix_error("sigprocmask error!");
  46.                 }
  47.         }
  48.         errno = olderrno;
  49.     return;
  50. }
复制代码
sigint_handler
  1. /*
  2. * sigint_handler - The kernel sends a SIGINT to the shell whenver the
  3. *    user types ctrl-c at the keyboard.  Catch it and send it along
  4. *    to the foreground job.  
  5. */
  6. void sigint_handler(int sig)
  7. {
  8.         int olderrno = errno;//保存和恢复errno
  9.         sigset_t mask, prev_mask;
  10.         if(sigfillset(&mask))
  11.         {
  12.                 unix_error("sigfillset error!");//阻塞所有信号
  13.         }
  14.         if(sigprocmask(SIG_SETMASK, &mask, &prev_mask))
  15.         {
  16.                 unix_error("sigprocmask error!");
  17.         }
  18.             pid_t pid = fgpid(jobs);
  19.         if(pid != 0)//对进程组发送SIGINT
  20.                 kill(-pid, sig);
  21.         if(sigprocmask(SIG_SETMASK, &prev_mask, NULL))
  22.         {
  23.                 unix_error("sigprocmask error!");
  24.         }
  25.         errno = olderrno;
  26.     return;
  27. }
复制代码
sigtstp_handler
  1. /*
  2. * sigtstp_handler - The kernel sends a SIGTSTP to the shell whenever
  3. *     the user types ctrl-z at the keyboard. Catch it and suspend the
  4. *     foreground job by sending it a SIGTSTP.  
  5. */
  6. void sigtstp_handler(int sig)
  7. {
  8.         int olderrno = errno;
  9.         sigset_t mask, prev_mask;
  10.         if(sigfillset(&mask))
  11.         {
  12.                 unix_error("sigfillset error!");//阻塞所有信号来访问全局变量
  13.         }
  14.         if(sigprocmask(SIG_SETMASK, &mask, &prev_mask))
  15.         {
  16.                 unix_error("sigprocmask error!");
  17.         }
  18.         pid_t pid = fgpid(jobs);
  19.         if(pid != 0)//向进程组发送SIGTSTP
  20.                 kill(-pid, sig);
  21.                
  22.         if(sigprocmask(SIG_SETMASK, &prev_mask, NULL))
  23.         {
  24.                 unix_error("sigprocmask error!");
  25.         }
  26.         errno = olderrno;
  27.     return;
  28. }
复制代码
测试

对比tsh和参考shell程序tshref,测试了16组例子。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

鼠扑

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表