计算机系统实验四

实验报告

验(四)

题     目      TinyShell         

     微壳            

专       业                     

学     号                     

班     级                   

学       生                 

指 导 教 师                    

实 验 地 点            

实 验 日 期                   

计算学部

 

第1章 实验基本信息... - 4 -

1.1 实验目的... - 4 -

1.2 实验环境与工具... - 4 -

1.2.1 硬件环境... - 4 -

1.2.2 软件环境... - 4 -

1.2.3 开发工具... - 4 -

1.3 实验预习... - 4 -

第2章 实验预习... - 6 -

2.1 进程的概念、创建和回收方法(5分)... - 6 -

2.2信号的机制、种类(5分)... - 6 -

2.3 信号的发送方法、阻塞方法、处理程序的设置方法(5分)... - 6 -

2.4 什么是shell,功能和处理流程(5分)... - 6 -

第3章 TinyShell的设计与实现... - 7 -

3.1.1 void eval(char *cmdline)函数(10分)... - 7 -

3. 1.2 int builtin_cmd(char **argv)函数(5分)... - 7 -

3. 1.3 void do_bgfg(char **argv) 函数(5分)... - 7 -

3. 1.4 void waitfg(pid_t pid) 函数(5分)... - 7 -

3. 1.5 void sigchld_handler(int sig) 函数(10分)... - 8 -

第4章 TinyShell测试... - 9 -

4.1 测试方法... - 9 -

4.2 测试结果评价... - 9 -

4.3 自测试结果... - 9 -

4.3.1测试用例trace01.txt的输出截图(1分)... - 9 -

4.3.2测试用例trace02.txt的输出截图(1分)... - 9 -

4.3.3测试用例trace03.txt的输出截图(1分)... - 10 -

4.3.4测试用例trace04.txt的输出截图(1分)... - 10 -

4.3.5测试用例trace05.txt的输出截图(1分)... - 10 -

4.3.6测试用例trace06.txt的输出截图(1分)... - 11 -

4.3.7测试用例trace07.txt的输出截图(1分)... - 11 -

4.3.8测试用例trace08.txt的输出截图(1分)... - 11 -

4.3.9测试用例trace09.txt的输出截图(1分)... - 12 -

4.3.10测试用例trace10.txt的输出截图(1分)... - 12 -

4.3.11测试用例trace11.txt的输出截图(1分)... - 12 -

4.3.12测试用例trace12.txt的输出截图(1分)... - 13 -

4.3.13测试用例trace13.txt的输出截图(1分)... - 13 -

4.3.14测试用例trace14.txt的输出截图(1分)... - 13 -

4.3.15测试用例trace15.txt的输出截图(1分)... - 14 -

4.4 自测试评分... - 14 -

第4章 总结... - 15 -

4.1 请总结本次实验的收获... - 15 -

4.2 请给出对本次实验内容的建议... - 15 -

参考文献... - 16 -

第1章 实验基本信息

1.1 实验目的

理解现代计算机系统进程与并发的基本知识

掌握linux 异常控制流和信号机制的基本原理和相关系统函数

掌握shell的基本原理和实现方法

深入理解Linux信号响应可能导致的并发冲突及解决方法

培养Linux下的软件系统开发与测试能力

1.2 实验环境与工具

1.2.1 硬件环境

X64 CPU;2GHz;2G RAM;256GHD Disk 以上

1.2.2 软件环境

Windows7/10 64位以上;VirtualBox/Vmware 11以上;Ubuntu 16.04 LTS 64位/优麒麟 64位 以上;

1.2.3 开发工具

Visual Studio 2010 64位以上;CodeBlocks 64位;vi/vim/gedit+gcc

1.3 实验预习

上实验课前,必须认真预习实验指导书(PPT或PDF)

了解实验的目的、实验环境与软硬件工具、实验操作步骤,复习与实验有关的理论知识。

了解进程、作业、信号的基本概念和原理

了解shell的基本原理

熟知进程创建、回收的方法和相关系统函数

熟知信号机制和信号处理相关的系统函数

第2章 实验预习

总分20

2.1 进程的概念、创建和回收方法(5分)

进程:一个执行中程序的1实例

进程的创建:通过fork()创建进程

进程的回收:pid_t waitpid(pid_t pid,int *status,int cptains),pid为指定回收进程的pid

> 0:待回收的子进程pid

> -1:任意子进程。

=0:同组的子进程

<-1:进程组号为pid绝对值的任何子进程。

2.2信号的机制、种类(5分)

机制:1)发送信号。发送信号的程序用系统调用kill( )实现;

2)预置对信号的处理方式。接收信号的程序用signal( )来实现对处理方式的预置;

3)收受信号的进程按事先的规定完成对相应事件的处理。     

种类:

  1. 与进程终止相关的信号。当进程退出,或者子进程终止时,发出这类信号。
  2. 与进程例外事件相关的信号。如进程越界。
  3. 与在系统调用期间遇到不可恢复条件相关的信号。如执行系统调用exec时,原有资源已经释放,而目前系统资源又已经耗尽。
  4. 与执行系统调用时遇到非预测错误条件相关的信号。如执行一个并不存在的系统调用。
  5. 在用户态下的进程发出的信号。如进程调用系统调用kill向其他进程发送信号。
  6. 与终端交互相关的信号。如用户关闭一个终端,或按下break键等情况。
  7. 跟踪进程执行的信号。

2.3 信号的发送方法、阻塞方法、处理程序的设置方法(5分)

信号的发送方法:

1. 用 /bin/kill 程序发送信号

2. 从键盘发送信号

3. 用 kill 函数发送信号

信号的阻塞方法:

1.隐式阻塞机制:内核默认阻塞与当前正在处理信号类型相同的待处理信号

2. 显示阻塞和解除阻塞机制:

sigprocmask 函数及其辅助函数可以明确地阻塞/解除阻塞

选定的信号:SIG_   BLOCK/UNBLOCK/SET_MASK

辅助函数:sigemptyset – 初始化set为空集合

sigfillset – 把每个信号都添加到set中

sigaddset – 把指定的信号signum添加到set

sigdelset – 从set中删除指定的信号signum

2.4 什么是shell,简述其功能和处理流程(5分)

功能:shell是一个交互型应用级程序,代表用户运行其他程序

处理流程:

1.通过读步骤来读取用户的命令行

2.求值步骤来解析命令

3.代表用户运行

第3章 TinyShell的设计与实现

总分45

3.1 设计

3.1.1 void eval(char *cmdline)函数(10分)

函数功能:解析和解释命令行的主例程

参    数:char *cmdline即输入的命令行字符串

处理流程:

1.解析命令行,如果argv[0]=NULL,即全路径名为空,直接返回,忽略空的命令行。

2.设置信号掩码,将SIGCHLD, SIGINT, SIGTSTP信号进行阻塞,直到将作业添加到作业列表,如果设置失败则报错。

3.创建子进程,创建失败时报错。

4.运行子进程,先更新信号掩码,将SIGCHLD, SIGINT, SIGTSTP解除阻塞,然后用进程本身的pid来命名进程组pid,在新的作业中运行程序,如果运行失败输出Command not found。

5.根据bg将作业添加到对应的作业列表,如果是前台作业则等待结束,对于后台作业直接打印信息

要点分析:

1.通过信号掩码先添加SIGCHLD, SIGINT, SIGTSTP来消除添加作业到信号列表和SIGCHLD, SIGINT, SIGTSTP的到达之间的冲突。

2.对应每步出错都有报错。

3. 1.2 int builtin_cmd(char **argv)函数(5分)

函数功能:识别并解释内置命令: quit, fg, bg, 和 jobs。

参    数:char **argv[] 表示传入函数的参数序列

处理流程:

1.比较是否输入quit,若是则直接退出。

2.若不是,比较是否输入jobs,若是则直接执行listjobs(jobs),并返回1

3.若不是,比较是否输入bg或fg,若是则执行do_bgfg,并返回1

4.若均不是则返回0表示未输入内置命令。

要点分析:

1.判断输入命令行是否为内置命令,是则立即执行,不是返回0;

3. 1.3 void do_bgfg(char **argv) 函数(5分)

函数功能:实现内置命令bg 和 fg

参    数:char **argv[] 表示传入函数的参数序列

处理流程:

1.忽略没有参数的指令,如果argv[1]为空则输出提示信息并返回

2.分析需要的PID或者%JID参数,如果没有相对应的PID或JID参数在jobs中,输出提示信息并返回,如果argv[1]不是PID或%JID参数,则输出提示并返回。

3.若输入的是bg指令,则将停止的后台作业转换为运行的后台作业,作业状态赋为BG,并打印信息。若输入的是fg指令,则将运行或停止的后台作业转换为运行的后台作业,将作业状态赋值为FG,并打印信息。

4.如果均不是,打印提示信息并退出

要点分析:

1.第一步是对参数进行检查,如果输入参数不在jobs中或者不符合规范,则直接返回。

2.第二步是对指令进行检查,输入bg或fg成功执行,否则直接退出。

3. 1.4 void waitfg(pid_t pid) 函数(5分)

函数功能:等待一个前台作业结束

参    数:指定前台作业的pid

处理流程:当fg_completed=0时持续休眠直到fg_completed=1时返回

要点分析:使用busy loop实现等待前台作业结束

3. 1.5 void sigchld_handler(int sig) 函数(10分)

函数功能:捕获SIGCHILD信号

参    数:int sig

处理流程:

1.获取当前作业的pid,如果是前台作业,直接让waitpid跳出循环。

2.根据子进程结束状态进行相关操作,若子进程正常结束则删除对应作业,否则若子进程因信号而结束,打印信息并且删除对应作业,否则若子进程处于暂停状态,则打印信息并且修改state

要点分析:

注意信号并不会叠加,所以无法得知有几个SIGCHILD信号,使用while而不是if

3.2 程序实现(tsh.c的全部内容)(10分)

重点检查代码风格:

  1. 用较好的代码注释说明——5
  2. 检查每个系统调用的返回值——5

第4章 TinyShell测试

总分15

4.1 测试方法

针对tsh和参考shell程序tshref,完成测试项目4.1-4.15的对比测试,并将测试结果截图或者通过重定向保存到文本文件(例如:./sdriver.pl -t trace01.txt -s ./tsh -a "-p" > tshresult01.txt)。

4.2 测试结果评价

tsh与tshref的输出在一下两个方面可以不同:

(1)PID

(2)测试文件trace11.txt, trace12.txt和trace13.txt中的/bin/ps命令,每次运行的输出都会不同,但每个mysplit进程的运行状态应该相同。

除了上述两方面允许的差异,tsh与tshref的输出相同则判为正确,如不同则给出原因分析。

第4章 总结

4.1 请总结本次实验的收获

1.本次实验我复习了进程,作业,信号的基本概念以及原理,加深了对于进程与信号的了解。

2.认识到了shell的基本原理,感觉掌握的更加扎实了

3.熟悉了信号的机制以及信号处理相关的系统函数

4.了解了如何创建进程,回收进程。

4.2 请给出对本次实验内容的建议

希望老师能实现说明一下在泰山服务器上运行需要注意的问题以及相关的操作。

注:本章为酌情加分项。

参考文献

为完成本次实验你翻阅的书籍与网站等

[1]  林来兴. 空间控制技术[M]. 北京:中国宇航出版社,1992:25-42.

[2]  辛希孟. 信息技术与信息服务国际研讨会论文集:A集[C]. 北京:中国科学出版社,1999.

[3]  赵耀东. 新时代的工业工程师[M/OL]. 台北:天下文化出版社,1998 [1998-09-26]. http://www.ie.nthu.edu.tw/info/ie.newie.htm(Big5).

[4]  谌颖. 空间交会控制理论与方法研究[D]. 哈尔滨:哈尔滨工业大学,1992:8-13.

[5]  KANAMORI H. Shaking Without Quaking[J]. Science,1998,279(5359):2063-2064.

[6]  CHRISTINE M. Plant Physiology: Plant Biology in the Genome Era[J/OL]. Science,1998,281:331-332[1998-09-23]. http://www.sciencemag.org/cgi/ collection/anatmorp.

源码如下:

/*
 * tsh - A tiny shell program with job control
 *
 * <Put your name and login ID here>
 */
#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 */
volatile sig_atomic_t fg_completed = 0;//当前台的作业停止或结束时,置为1,否则置为0

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);
        fflush(stdout);
        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)
{
    /* $begin handout */
    char *argv[MAXARGS]; /* argv for execve() 存放指向你的字符串参数的指针*/
    int bg;              /* should the job run in bg or fg? */
    pid_t pid;           /* process id */
    sigset_t mask;       /* signal mask 信号掩码*/

    /* Parse command line 解析命令行*/
    bg = parseline(cmdline, argv);
    if (argv[0] == NULL) //全路径名为空
        return;   /* ignore empty lines */

    if (!builtin_cmd(argv))
    {

        /*
        * 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.
         */

        if (sigemptyset(&mask) < 0)//sigemptyset()用来将参数set 信号集初始化并清空.
            unix_error("sigemptyset error");
        if (sigaddset(&mask, SIGCHLD)) //向信号集添加SIGCHLD 终止时向父进程发送
            unix_error("sigaddset error");
        if (sigaddset(&mask, SIGINT))
            unix_error("sigaddset error");
        if (sigaddset(&mask, SIGTSTP))
            unix_error("sigaddset error");
        if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0)//
            unix_error("sigprocmask error");

        /* Create a child process */
        if ((pid = fork()) < 0)
            unix_error("fork error");

        /*
         * Child  process
         */

        if (pid == 0)
        {
            /* Child unblocks signals */
            sigprocmask(SIG_UNBLOCK, &mask, NULL);//更新信号掩码

            /* Each new job must get a new process group ID
               so that the kernel doesn't send ctrl-c and ctrl-z
               signals to all of the shell's jobs */
            if (setpgid(0, 0) < 0) //用进程本身的pid来命名组pid
                unix_error("setpgid error");

            /* Now load and run the program in the new job */
            if (execve(argv[0], argv, environ) < 0)
            {
                printf("%s: Command not found\n", argv[0]);
                exit(0);
            }
        }

        /*
         * Parent process
         */

        /* Parent adds the job, and then unblocks signals so that
           the signals handlers can run again */
        addjob(jobs, pid, (bg == 1 ? BG : FG), cmdline);
        sigprocmask(SIG_UNBLOCK, &mask, NULL);

        if (!bg)
            waitfg(pid);
        else
            printf("[%d] (%d) %s", pid2jid(pid), pid, cmdline);
    }
    /* $end handout */
    return;
}

/*
 * 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)
{
    if (!strcmp(argv[0], "quit"))//判断是否为quit
        exit(1);
    else if (!strcmp(argv[0], "jobs"))//判断是否为jobs
    {
        listjobs(jobs);
        return 1;
    }
    else if (!strcmp(argv[0], "bg") || !strcmp(argv[0], "fg"))//判断是否为bg或fg
    {
        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)
{
    /* $begin handout */
    struct job_t *jobp=NULL;

    /* Ignore command if no argument */
    if (argv[1] == NULL)
    {
        printf("%s command requires PID or %%jobid argument\n", argv[0]);
        return;
    }

    /* Parse the required PID or %JID arg */
    if (isdigit(argv[1][0]))
    {
        pid_t pid = atoi(argv[1]);
        if (!(jobp = getjobpid(jobs, pid)))
        {
            printf("(%d): No such process\n", pid);
            return;
        }
    }
    else if (argv[1][0] == '%')
    {
        int jid = atoi(&argv[1][1]);
        if (!(jobp = getjobjid(jobs, jid)))
        {
            printf("%s: No such job\n", argv[1]);
            return;
        }
    }
    else
    {
        printf("%s: argument must be a PID or %%jobid\n", argv[0]);
        return;
    }

    /* bg command */
    if (!strcmp(argv[0], "bg"))
    {
        if (kill(-(jobp->pid), SIGCONT) < 0)
            unix_error("kill (bg) error");
        jobp->state = BG;
        printf("[%d] (%d) %s", jobp->jid, jobp->pid, jobp->cmdline);
    }

    /* fg command */
    else if (!strcmp(argv[0], "fg"))
    {
        if (kill(-(jobp->pid), SIGCONT) < 0)
            unix_error("kill (fg) error");
        jobp->state = FG;
        waitfg(jobp->pid);
    }
    else
    {
        printf("do_bgfg: Internal error\n");
        exit(0);
    }
    /* $end handout */
    return;
}

/*
 * waitfg - Block until process pid is no longer the foreground process
 */
void waitfg(pid_t pid)
{

    fg_completed = 0;

    while (!fg_completed)//采用busy loop
    {
        sleep(1);
    }
    return;
}

/*****************
 * 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.
 */
void sigchld_handler(int sig)
{
    int olderrno = errno;//错误代码
    pid_t pid;
    struct job_t *job_now;
    int sta;
    sigset_t mask_all, mask_prev;


    if (sigfillset(&mask_all) < 0)//检查sigfillset是否正常
            unix_error("sigfillset error");
    //pending signals are not queued!用while而不是if
    while ((pid = waitpid(-1, &sta, WNOHANG | WUNTRACED)) > 0) {
        //在访问全局变量时,不能被信号处理程序中断,所以阻塞所有信号。
         if (sigprocmask(SIG_BLOCK, &mask_all, &mask_prev) < 0)//
            unix_error("sigprocmask error");
        job_now = getjobpid(jobs, pid);
        //如果是前台任务,修改fg_completed,让waitfg跳出循环
        if (job_now->state == FG) fg_completed = 1;
        if (WIFEXITED(sta)) {
            //子进程正常结束,删除对应任务
            deletejob(jobs, pid);
        } else if (WIFSIGNALED(sta)) {
            //子进程因信号而结束,打印相关信息并删除对应任务
            printf("Job [%d] (%d) terminated by signal %d\n", job_now->jid, job_now->pid, WTERMSIG(sta));
            deletejob(jobs, pid);
        } else if (WIFSTOPPED(sta)) {
            //子进程处于暂停状态,打印相关信息并修改state
            printf("Job [%d] (%d) stopped by signal %d\n", job_now->jid, job_now->pid, WSTOPSIG(sta));
            job_now->state = ST;
        }
        if (sigprocmask(SIG_SETMASK, &mask_prev, NULL) < 0)//
            unix_error("sigprocmask error");

    }
    errno = olderrno;
    return;
}

/*
 * 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)
{
    int olderrno = errno;
    pid_t pid;
    sigset_t mask_all, mask_prev;

    if (sigfillset(&mask_all) < 0)//检查sigfillset是否正常
            unix_error("sigfillset error");
    //在访问全局变量时,不能被信号处理程序中断,故阻塞所有信号。
     if (sigprocmask(SIG_BLOCK, &mask_all, &mask_prev) < 0)//检查sigprocmask是否正常
            unix_error("sigprocmask error");
    pid = fgpid(jobs);//foreground job pid
    if (sigprocmask(SIG_SETMASK, &mask_prev, NULL) < 0)//检查sigprocmask是否正常
            unix_error("sigprocmask error");
    if (pid != 0) {
        //向前台进程组发送SIGINT,故是-pid(子进程的进程组ID与PID相同)
        kill(-pid, SIGINT);
    }
    errno = olderrno;
    return;
}

/*
 * 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)
{
    int olderrno = errno;
    pid_t pid;
    sigset_t mask_all, mask_prev;

    sigfillset(&mask_all);
    //在访问全局变量时,不能被信号处理程序中断,故阻塞所有信号。
    if (sigprocmask(SIG_BLOCK, &mask_all, &mask_prev) < 0)//检查sigprocmask是否正常
            unix_error("sigprocmask error");
    pid = fgpid(jobs);//foreground job pid
    if (sigprocmask(SIG_SETMASK, &mask_prev, NULL) < 0)//检查sigprocmask是否正常
            unix_error("sigprocmask error");
    if (pid != 0) {
        //向前台进程组发送SIGTSTP,故是-pid(子进程的进程组ID与PID相同)
        kill(-pid, SIGTSTP);
    }
    errno = olderrno;
    return;

}

/*********************
 * 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)
        {
            jobs[i].pid = pid;
            jobs[i].state = state;
            jobs[i].jid = nextjid++;
            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)
{
    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)
{
    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)
{
    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);
}



Y86 Tools (Student Distribution) Copyright (c) 2002, R. Bryant and D. O Hallaron, All rights reserved. May not be used, modified, or copied without permission. This directory contains the student distribution of the Y86 tools. It is a proper subset of the master distribution, minus the solution files found in the master distribution. yas Y86 assembler yis Y86 instruction (ISA) simulator hcl2c HCL to C translator ssim SEQ simulator ssim+ SEQ+ simulator psim PIPE simulator y86-code/ Examples programs and and benchmark testing scripts ptest/ Scripts for detailed automated regression testing 1. Building the Y86 tools The Y86 simulators can be configured to support TTY and GUI interfaces. A simulator running in TTY mode prints all information about its run-time behavior on the terminal. Hard to understand what s going on, but useful for automated testing, and doesn t require any special installation features. A simulator running in GUI mode uses a fancy graphical user interface. Nice for visualizing and debugging, but requires installation of Tcl/Tk on your system. To build the Y86 tools, perform the following steps: NOTE: If your instructor prepared this distribution for you, then you can skip Step 1 and proceed directly to Step 2. The Makefile will already have the proper values for GUIMODE, TKLIBS, and TKINC for your system. Step 1. Decide whether you want the TTY or GUI form of the simulators, and then modify ./Makefile in this directory accordingly. (The changes you make to the variables in this Makefile will override the values already assigned in the Makefiles in the seq and pipe directories.) Building the GUI simulators: If you have Tcl/Tk installed on your system, then you can build the GUI form by initializing the GUIMODE, TKLIBS, and TKINC variables, as appropriate for your system. (The default values work for Linux systems.) Assigning GUIMODE=-DHAS_GUI causes the necessary GUI support code in the simulator sources to be included. The TKLIBS variable tells gcc where to look for the libtcl.so and libtk.so libraries. And the TKINC variable tells gcc where to find the tcl.h and tk.h header files. Building the TTY simulators: If you don t have Tcl/Tk installed on your system, then build the TTY form by commenting out all three of these variables (GUIMODE, TKLIBS, and TKINC) in the Makefile. Step 2: Once you ve modified the Makefile to build either the GUI or TTY form, then you can construct the entire set of Y86 tools by typing unix> make clean; make 2. Files Makefile Builds the Y86 tools README This file misc/ Source files for the Y86 assembler yas, the Y86 instruction simulator yis, and the isa.c file that is used by the -t option of the processor simulators to check the results against the ISA simulation. seq/ Code for the SEQ and SEQ+ simulators. Contains HCL files for labs and homework problems that involve modifying SEQ. pipe/ Code for the PIPE simulator. Contains HCL files for labs and homework problems that involve modifying PIPE. y86-code/ Example .ys files from CS:APP and scripts for conducting automated benchmark teseting of the new processor designs. ptest/ Automated regression testing scripts for testing processor designs.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值