CSAPP shell lab实验 educoder题解全1~16关

序言

大二上的时候学csapp的最后一个实验,本身exceptional control flow就挺难理解的,然后做这个实验的时候也是遇到了很多的困难。网上的题解都是给出了全部函数,没有educoder版的一步一步的,正好这次老师助教没有要求写实验报告,我就把我的解题思路在csdn上写一篇吧,也方便后续做实验的的学弟学妹留做参考;

在直接看题解之前:

  1. I strongly recommend you that you should read the csapp book first!!! 书上写得很不错,几乎所有的函数都能在书上找到原型,把第八章的书彻彻底底的吃透了你才能从技术层面知道究竟做了什么事;
  2. 本身educoder是有代码查重的,我希望你可以看懂之后独立完成你的代码;
  3. 这个实验educoder提供了官方文档,官方文档提供了有用的东西;

熟悉实验环境

先cd进myshixun,然后用ls命令查看该目录下的文件
trace是我们的目标文件
还有一些小程序用来执行的,如myint myspin 感兴趣的话可以用vim打开查看下
(很简单的c代码)
在命令行里测试的时候使用make命令会生成对应的tsh文件
再执行./tsh
进入命令行测试

然后我们看一下这个shell具体做了哪些事情:

在这里插入图片描述
定义了一些宏,以及四种进程的状态:
UNDEF FG(前台运行) BG(后台运行) ST(挂起状态)
在这里插入图片描述
然后定义了job_t的任务的类,并且创建了jobs[]数组
在这里插入图片描述
需要我们完成以上函数的具体实现
在这里插入图片描述

并且给出了一些函数辅助我们;
这里需要我们找到这些函数大致明白他们的作用
parseline来提取命令行关键字
initjob初始化任务jobs[]
maxjid得到创建进程的最大jid
addjob添加一个任务
deletejob删除一个任务
getjobpid getjobjid分别根据pid和jid的值找到对应的任务job
pid2jid根据pid找到jid
listjob例举出所有进程

main函数在文件中逐行获取命令(这里不需要全部看懂)
并且判断是不是文件结束(EOF)
install了对于子进程/ctrl-z/ctrl_c的终端信号的handler
将命令cmdline送入eval函数进行解析
我们需要做的就是逐步完善这个过程

第一关

输入
    #
    # t\frace01.txt - Properly terminate on EOF.
    #
    CLOSE
    WAIT
预期输出:
    #
    # t\frace01.txt - Properly terminate on EOF.
    #

#可以理解为//,不需要我们解析
第一关调用了linux命令close关闭文件并wait等待,所以不需要我们做任何事~~~

第二关

    #
    # t\frace02.txt - Process builtin quit command.
    #
    quit
    WAIT

    #
    # t\frace02.txt - Process builtin quit command.
    #

需我们针对输入的命令quit退出shell进程,我们需要解析cmdline,判断是不是“quit”字符串,是就退出
这里可以仿照书上的写法

void eval(char *cmdline) 
{
    char *argv[MAXARGS];
    char buf[MAXLINE];
    int bg;
    pid_t pid;
    strcpy(buf,cmdline);
    bg=parseline(buf,argv);
    builtin_cmd(argv);//读取到quit就退出了
    return;
}
int builtin_cmd(char **argv) 
{
    if(!strcmp(argv[0],"quit"))exit(0);
    return 0;     /* not a builtin command */
}

第三关

    #
    # t\frace03.txt - Run a foreground job.
    #
    /bin/echo tsh> quit
    quit
    
    #
    # t\frace03.txt - Run a foreground job.
    #
    tsh> quit

这里讲一下/bin/echo
eval函数先通过builtin_cmd查询cmdline是不是内置命令如quit,如果是则实行
如果不是则创建一个子进程,在子进程中调用 execve()函数通过 argv[0]来寻找路径,并在子进程中运行路径中的可执行文件,如果找不到则说明命令为无效命令,输出命令无效,并用 exit(0)结束该子进程
/bin/echo就是打开bin目录下的echo文件,echo可以理解为将其后面的内容当作字符串输出(当然先经过parseline翻译,echo比较复杂,感兴趣可以去查一下)
所以这里的意思就是eval发现/bin/echo不是内置命令,查询路径找到了echo程序并且在前台执行,输出了其后面的一句话。

void eval(char *cmdline) 
{
    char *argv[MAXARGS];
    char buf[MAXLINE];
    int bg;
    pid_t pid;
    strcpy(buf,cmdline);
    bg=parseline(buf,argv);
    if(argv[0]==NULL)return;
    if(!builtin_cmd(argv)){
        if((pid=fork())==0){
            if(execve(argv[0],argv,environ)<0){
                printf("%s: command not found.\n",argv[0]);
                exit(0);
            }
        }
    }
    return;
}
int builtin_cmd(char **argv) 
{
    if(!strcmp(argv[0],"quit"))exit(0);
    return 0;     /* not a builtin command */
}

第四关

    #
    # t\frace04.txt - Run a background job.
    #
    /bin/echo -e tsh> ./myspin 1 \046
    ./myspin 1 &
    #
    # t\frace04.txt - Run a background job.
    #
    tsh> ./myspin 1 &
    [1] (pid) ./myspin 1 &

先在前台执行echo命令,等待程序执行完毕回收子进程
这里需要注意为了避免addjob和deletejob竞争,我们需要添加阻塞
&代表是一个后台程序
然后在后台执行myspin程序并且输出任务ID(jid),程序ID(pid) 命令行(cmdline)

void eval(char *cmdline) 
{
    char *argv[MAXARGS];
    char buf[MAXLINE];
    int bg;
    pid_t pid;
    strcpy(buf,cmdline);
    bg=parseline(buf,argv);
    if(argv[0]==NULL)return;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask,SIGCHLD);
    sigprocmask(SIG_BLOCK,&mask,NULL);
    if(!builtin_cmd(argv)){
        if((pid=fork())==0){
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            setpgid(0,0);
            if(execve(argv[0],argv,environ)<0){
                printf("%s: command not found.\n",argv[0]);
                exit(0);
            }
        }
        if(!bg){
        //前台程序添加工作父进程后解除阻塞,可以接收SIGCHILD来回收子进程,通过waitfg等待;
            addjob(jobs,pid,FG,cmdline);
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            waitfg(pid);
        }
        else{
        //后台进程则不需要等待子进程,什么时候结束直接回收就可以了
            addjob(jobs,pid,BG,cmdline);
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            printf("[%d] (%d) %s",pid2jid(pid),pid,cmdline);
        }
    }
    return;
}
int builtin_cmd(char **argv) 
{
    if(!strcmp(argv[0],"quit"))exit(0);
    return 0;     /* not a builtin command */
}
//这里我们用sigsuspend,根据子进程是否结束,发出SIG_CHILD来决定是否返回;
void waitfg(pid_t pid)
{
    sigset_t mask;
    sigemptyset(&mask);
    while(pid==fgpid(jobs))sigsuspend(&mask);
    return;
}
void sigchld_handler(int sig) 
{
    pid_t pid;
    int status;
    while((pid=waitpid(-1,&status,WNOHANG|WUNTRACED))>0){      
        if(WIFEXITED(status))deletejob(jobs,pid);
        //如果正确退出了则代表子进程运行完毕,就删除掉这个任务
    }
    return;
}

第五关

    #
    # t\frace05.txt - Process jobs builtin command.
    #
    /bin/echo -e tsh> ./myspin 2 \046
    ./myspin 2 &
    /bin/echo -e tsh> ./myspin 3 \046
    ./myspin 3 &
    /bin/echo tsh> jobs
    jobs
    #
    # t\frace05.txt - Process jobs builtin command.
    #
    tsh> ./myspin 2 &
    [1] (pid) ./myspin 2 &
    tsh> ./myspin 3 &
    [2] (pid) ./myspin 3 &
    tsh> jobs
    [1] (pid) Running ./myspin 2 &
    [2] (pid) Running ./myspin 3 &

分别运行了前台echo、后台myspin、前台echo、后台myspin
然后需要实现一个内置命令job,功能是显示目前任务列表中的所有任务的所有属性,这里可以利用listjob函数

//其他的都不需要改变
int builtin_cmd(char **argv) 
{
    if(!strcmp(argv[0],"quit"))exit(0);
    if(!strcmp(argv[0],"jobs")){
        listjobs(jobs);
        return 1;
    }
    return 0;     /* not a builtin command */
}

第六关

    #
    # t\frace06.txt - Forward SIGINT to foreground job.
    #
    /bin/echo -e tsh> ./myspin 4
    ./myspin 4 
    SLEEP 2
    INT
    #
    # t\frace06.txt - Forward SIGINT to foreground job.
    #
    tsh> ./myspin 4
    Job [1] (pid) terminated by signal 2

如果接收到了中断信号SIGINT(即CTRL_C)那么结束前台进程

void sigint_handler(int sig) 
{
    pid_t pid=fgpid(jobs);//找到前台进程的pid
    kill(-pid,SIGINT);//发送终止信号
    return;
}
void sigchld_handler(int sig) 
{
    pid_t pid;
    int status;
    while((pid=waitpid(-1,&status,WNOHANG|WUNTRACED))>0){      
        if(WIFEXITED(status))deletejob(jobs,pid);//正常终止
        if(WIFSIGNALED(status)){//由于接收信号终止
            deletejob(jobs,pid);
            printf("Job [%d] (%d) terminated by signal %d\n",pid2jid(pid),pid,WTERMSIG(status));
            //注意这里这个\n换行,这里是需要连续接受输出命令行的,需要换到下一行继续
            /*
            这个printf你会发现写在sigint_handler里也可以通过,
            不过那样意义是不一样的,这么写意思是我发现子程序由于SIGINT信号中断而终止所以输出这句话
            写在handler里意味着在识别到trace文件中的INT就输出了,与子程序无关
            这会导致来自外界的信号而不是trace文件中的信号无法别识别,你会在第十六关发现不同
            */
        }
    }
    return;
}

第七关

    #
    # t\frace07.txt - Forward SIGINT only to foreground job.
    #
    /bin/echo -e tsh> ./myspin 4 \046
    ./myspin 4 &
    /bin/echo -e tsh> ./myspin 5
    ./myspin 5 
    SLEEP 2
    INT
    /bin/echo tsh> jobs
    jobs
    #
    # t\frace07.txt - Forward SIGINT only to foreground job.
    #
    tsh> ./myspin 4 &
    [1] (pid) ./myspin 4 &
    tsh> ./myspin 5
    Job [2] (pid) terminated by signal 2
    tsh> jobs
    [1] (pid) Running ./myspin 4 &

第七关是检测你之前是否是正确完成了所有的函数,有没有投机取巧
不需要改动,直接通过~~~

第八关

    #
    # t\frace08.txt - Forward SIGTSTP only to foreground job.
    #
    /bin/echo -e tsh> ./myspin 4 \046
    ./myspin 4 &
    
    /bin/echo -e tsh> ./myspin 5
    ./myspin 5 
    
    SLEEP 2
    TSTP
    
    /bin/echo tsh> jobs
    jobs
    #
    # t\frace08.txt - Forward SIGTSTP only to foreground job.
    #
    tsh> ./myspin 4 &
    [1] (pid) ./myspin 4 &
    tsh> ./myspin 5
    Job [2] (pid) stopped by signal 20
    tsh> jobs
    [1] (pid) Running ./myspin 4 &
    [2] (pid) Stopped ./myspin 5

这里有空命令行,所以需要在eval里加一句判断是否是空(我加在之前的eval里了)
当接收到了TSTP中断信号(即CTRL_Z),将前台进程挂起,然后输出被挂起的任务

void sigtstp_handler(int sig) 
{
    pid_t pid=fgpid(jobs);
    kill(-pid,SIGTSTP);//找到前台任务发送挂起信号
    return;
}
void sigchld_handler(int sig) 
{
    pid_t pid;
    int status;
    while((pid=waitpid(-1,&status,WNOHANG|WUNTRACED))>0){      
        if(WIFEXITED(status))deletejob(jobs,pid);
        if(WIFSIGNALED(status)){
            deletejob(jobs,pid);
            printf("Job [%d] (%d) terminated by signal %d\n",pid2jid(pid),pid,WTERMSIG(status));
        }
        if(WIFSTOPPED(status)){
        //找到前台任务然后改变其运行状态为挂起(ST)
            struct job_t *job=getjobpid(jobs,pid);
            job->state=ST;
            printf("Job [%d] (%d) stopped by signal %d\n",pid2jid(pid),pid,WSTOPSIG(status));
        }
    }
    return;
}

第九关

    #
    # t\frace09.txt - Process bg builtin command
    #
    /bin/echo -e tsh> ./myspin 4 \046
    ./myspin 4 &
    /bin/echo -e tsh> ./myspin 5
    ./myspin 5 
    SLEEP 2
    TSTP
    /bin/echo tsh> jobs
    jobs
    /bin/echo tsh> bg %2
    bg %2
    /bin/echo tsh> jobs
    jobs
    #
    # t\frace09.txt - Process bg builtin command
    #
    tsh> ./myspin 4 &
    [1] (pid) ./myspin 4 &
    tsh> ./myspin 5
    Job [2] (pid) stopped by signal 20
    tsh> jobs
    [1] (pid) Running ./myspin 4 &
    [2] (pid) Stopped ./myspin 5 
    tsh> bg %2
    [2] (pid) ./myspin 5 
    tsh> jobs
    [1] (pid) Running ./myspin 4 &
    [2] (pid) Running ./myspin 5 

九十两关创建了内置命令bg fg
我们在代码里可以找到他们的意思
在这里插入图片描述
bg命令是将一个挂起的程序转到后台继续执行
fg命令是将一个挂起的程序转到前台继续执行,或者将一个后台执行的程序转到前台执行

int builtin_cmd(char **argv) 
{
    if(!strcmp(argv[0],"quit"))exit(0);
    if(!strcmp(argv[0],"jobs")){
        listjobs(jobs);
        return 1;
    }
    if(!strcmp(argv[0],"bg")){
        do_bgfg(argv);
        return 1;
    }
    return 0;     /* not a builtin command */
}
void do_bgfg(char **argv) 
{
    int jid;
    struct job_t *job;
    if(!strcmp(argv[0],"bg")){
        jid=atoi(&argv[1][1]);
        //这里利用了系统atoi函数,传入参数是字符串首地址,返回该字符串的所代表的数字
        //当然你也可以写成jid=argv[1][1]-'0',当然详细点就是加个循环将整个字符串扫一遍;
        job=getjobjid(jobs,jid);
        job->state=BG;
        kill(-(job->pid),SIGCONT);
        /*
        这里你会发现不写kill依然可以过,但是意义不同
        你这里只是机械性的在任务列表中改变了它的state,并没有本质上改变他的进程状态
        必须要用kill发送SIGCONT重启信号让这个进程真正的重启,进入后台运行状态才是正确的
        jobs[]只是记录了每个进程的信息
        */
        printf("[%d] (%d) %s", jid, job->pid, job->cmdline);  
    }
    return;
}

第十关

    #
    # t\frace10.txt - Process fg builtin command. 
    #
    /bin/echo -e tsh> ./myspin 4 \046
    ./myspin 4 &
    SLEEP 1
    /bin/echo tsh> fg %1
    fg %1
    SLEEP 1
    TSTP
    /bin/echo tsh> jobs
    jobs
    /bin/echo tsh> fg %1
    fg %1
    /bin/echo tsh> jobs
    jobs
    #
    # t\frace10.txt - Process fg builtin command. 
    #
    tsh> ./myspin 4 &
    [1] (pid) ./myspin 4 &
    tsh> fg %1
    Job [1] (pid) stopped by signal 20
    tsh> jobs
    [1] (pid) Stopped ./myspin 4 &
    tsh> fg %1
    tsh> jobs

之前我们提到了
bg命令是将一个挂起的程序转到后台继续执行
fg命令是将一个挂起的程序转到前台继续执行,或者将一个后台执行的程序转到前台执行

int builtin_cmd(char **argv) 
{
    if(!strcmp(argv[0],"quit"))exit(0);
    if(!strcmp(argv[0],"jobs")){
        listjobs(jobs);
        return 1;
    }
    if(!strcmp(argv[0],"bg")||!strcmp(argv[0],"fg")){
        do_bgfg(argv);
        return 1;
    }
    return 0;     /* not a builtin command */
}
void do_bgfg(char **argv) 
{
    int jid;
    struct job_t *job;
    if(!strcmp(argv[0],"bg")){
        jid=atoi(&argv[1][1]);
        job=getjobjid(jobs,jid);
        job->state=BG;
        kill(-(job->pid),SIGCONT);
        printf("[%d] (%d) %s", jid, job->pid, job->cmdline);  
    }
    else {
        jid=atoi(&argv[1][1]);
        job=getjobjid(jobs,jid);
        if(job->state==BG){
        //如果是后台程序就转到前台并等待结束
            job->state=FG;
            waitfg(job->pid);
        }
        else if(job->state==ST){
        //如果是挂起程序就重启并且转到前台,等待结束
            job->state=FG;
            kill(-(job->pid),SIGCONT);
            waitfg(job->pid);
        }
        //前台程序和后台程序主要差异就是shell会不会等待你结束
        //前台shell主动等待waitfg,然后回收掉
        //后台就是什么时候结束什么时候返回SIGCHILD,然后回收掉
    }
    return;
}

第十一关

不需要修改~~~

第十二关

不需要修改~~~
注意:
这里你可能会出现一个错误的进程显示
这与你的程序无关
只是由于educoder的测评系统的执行问题,如果你发现这里错误了,等待一小会儿,重新运行11关在执行12关,或者先运行13关在执行12关,或者关掉网页再打开执行12关

第十三关

不需要修改~~~

第十四关

    #
    # t\frace14.txt - Simple error handling
    #
    /bin/echo tsh> ./bogus
    ./bogus
    /bin/echo -e tsh> ./myspin 4 \046
    ./myspin 4 &
    /bin/echo tsh> fg
    fg
    /bin/echo tsh> bg
    bg
    /bin/echo tsh> fg a
    fg a
    /bin/echo tsh> bg a
    bg a
    /bin/echo tsh> fg 9999999
    fg 9999999
    /bin/echo tsh> bg 9999999
    bg 9999999
    /bin/echo tsh> fg %2
    fg %2
    /bin/echo tsh> fg %1
    fg %1
    SLEEP 2
    TSTP
    /bin/echo tsh> bg %2
    bg %2
    /bin/echo tsh> bg %1
    bg %1
    /bin/echo tsh> jobs
    jobs
    #
    # t\frace14.txt - Simple error handling
    #
    tsh> ./bogus
    ./bogus: Command not found
    tsh> ./myspin 4 &
    [1] (pid) ./myspin 4 &
    tsh> fg
    fg command requires PID or %jobid argument
    tsh> bg
    bg command requires PID or %jobid argument
    tsh> fg a
    fg: argument must be a PID or %jobid
    tsh> bg a
    bg: argument must be a PID or %jobid
    tsh> fg 9999999
    (9999999): No such process
    tsh> bg 9999999
    (9999999): No such process
    tsh> fg %2
    %2: No such job
    tsh> fg %1
    Job [1] (pid) stopped by signal 20
    tsh> bg %2
    %2: No such job
    tsh> bg %1
    [1] (pid) ./myspin 4 &
    tsh> jobs
    [1] (pid) Running ./myspin 4 &

本关主要是测试所有的命令,判断是否正确。这一关没有技术难关,我希望你能独立完成

我提醒一句:注意大小写! 注意标点! 注意空格!
如果发现程序超时或者报错的问题可以进控制台make看下语法报错

void eval(char *cmdline) 
{
    char *argv[MAXARGS];
    char buf[MAXLINE];
    int bg;
    pid_t pid;
    strcpy(buf,cmdline);
    bg=parseline(buf,argv);
    if(argv[0]==NULL)return;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask,SIGCHLD);
    sigprocmask(SIG_BLOCK,&mask,NULL);
    if(!builtin_cmd(argv)){
        if((pid=fork())==0){
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            setpgid(0,0);
            if(execve(argv[0],argv,environ)<0){
                printf("%s: Command not found\n",argv[0]);
                exit(0);
            }
        }
        if(!bg){
            addjob(jobs,pid,FG,cmdline);
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            waitfg(pid);
        }
        else{
            addjob(jobs,pid,BG,cmdline);
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            printf("[%d] (%d) %s",pid2jid(pid),pid,cmdline);
        }
    }
    return;
}
void do_bgfg(char **argv) 
{
    int jid;
    struct job_t *job;
    if(argv[1]==NULL){
        printf("%s command requires PID or %%jobid argument\n",argv[0]);
        return ;
    }
    if(argv[1][0]=='%'){
        jid=atoi(&argv[1][1]);
        job=getjobjid(jobs,jid);
        if(job==NULL){
            printf("%%%d: No such job\n",jid);
            return ;
        }
    }
    else if(isdigit(argv[1][0])){
        jid = atoi(argv[1]);        
        job=getjobjid(jobs,jid);
        if(job==NULL){
            printf("(%d): No such process\n",jid);
            return ;
        }

    }
    else {
        printf("%s: argument must be a PID or %%jobid\n",argv[0]);
        return ;
    }
    if(!strcmp(argv[0],"bg")){
        job->state=BG;
        kill(-(job->pid),SIGCONT);
        printf("[%d] (%d) %s", jid, job->pid, job->cmdline);  
    }
    else {
        if(job->state==BG){
            job->state=FG;
            waitfg(job->pid);
        }
        else if(job->state==ST){
            job->state=FG;
            kill(-(job->pid),SIGCONT);
            waitfg(job->pid);
        }
    }
    return;
}

第十五关

还是大小写和标点空格

void eval(char *cmdline) 
{
    char *argv[MAXARGS];
    char buf[MAXLINE];
    int bg;
    pid_t pid;
    strcpy(buf,cmdline);
    bg=parseline(buf,argv);
    if(argv[0]==NULL)return;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask,SIGCHLD);
    sigprocmask(SIG_BLOCK,&mask,NULL);
    if(!builtin_cmd(argv)){
        if((pid=fork())==0){
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            setpgid(0,0);
            if(execve(argv[0],argv,environ)<0){
                printf("%s:Command not found.\n",argv[0]);
                exit(0);
            }
        }
        if(!bg){
            addjob(jobs,pid,FG,cmdline);
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            waitfg(pid);
        }
        else{
            addjob(jobs,pid,BG,cmdline);
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            printf("[%d] (%d) %s",pid2jid(pid),pid,cmdline);
        }
    }
    return;
}
void do_bgfg(char **argv) 
{
    int jid;
    struct job_t *job;
    if(argv[1]==NULL){
        printf("%s command requires PID or %%jobid argument\n",argv[0]);
        return ;
    }
    if(argv[1][0]=='%'){
        jid=atoi(&argv[1][1]);
        job=getjobjid(jobs,jid);
        if(job==NULL){
            printf("%%%d:No such job\n",jid);
            return ;
        }
    }
    else if(isdigit(argv[1][0])){
        jid = atoi(argv[1]);        
        job=getjobjid(jobs,jid);
        if(job==NULL){
            printf("(%d): No such process\n",jid);
            return ;
        }

    }
    else {
        printf("%s: argument must be a PID or %%jobid\n",argv[0]);
        return ;
    }
    if(!strcmp(argv[0],"bg")){
        job->state=BG;
        kill(-(job->pid),SIGCONT);
        printf("[%d] (%d) %s", jid, job->pid, job->cmdline);  
    }
    else {
        if(job->state==BG){
            job->state=FG;
            waitfg(job->pid);
        }
        else if(job->state==ST){
            job->state=FG;
            kill(-(job->pid),SIGCONT);
            waitfg(job->pid);
        }
    }
    return;
}

第十六关

如果你之前的SIGINT和SIGTSTP都是像我一样在sigchild_handler输出的printf不用修改
直接提交
如果你是写在sigint_handler和sigtstp_handler里那你就会发现没有printf的输出,我在前面的注释里有写过原因

提交!测评!完成!ENJOY YOURSELF!

虽然是当个实验报告来写的,但是码字不易,如果对你有所帮助,希望点一个小小的赞能让更多的卡关的人看到,谢谢~

完整代码如下

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

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) 
{
    char *argv[MAXARGS];
    char buf[MAXLINE];
    int bg;
    pid_t pid;
    strcpy(buf,cmdline);
    bg=parseline(buf,argv);
    if(argv[0]==NULL)return;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask,SIGCHLD);
    sigprocmask(SIG_BLOCK,&mask,NULL);
    if(!builtin_cmd(argv)){
        if((pid=fork())==0){
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            setpgid(0,0);
            if(execve(argv[0],argv,environ)<0){
                printf("%s:Command not found.\n",argv[0]);
                exit(0);
            }
        }
        if(!bg){
            addjob(jobs,pid,FG,cmdline);
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            waitfg(pid);
        }
        else{
            addjob(jobs,pid,BG,cmdline);
            sigprocmask(SIG_UNBLOCK,&mask,NULL);
            printf("[%d] (%d) %s",pid2jid(pid),pid,cmdline);
        }
    }
    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"))exit(0);
    if(!strcmp(argv[0],"jobs")){
        listjobs(jobs);
        return 1;
    }
    if(!strcmp(argv[0],"bg")||!strcmp(argv[0],"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) 
{
    int jid;
    struct job_t *job;
    if(argv[1]==NULL){
        printf("%s command requires PID or %%jobid argument\n",argv[0]);
        return ;
    }
    if(argv[1][0]=='%'){
        jid=atoi(&argv[1][1]);
        job=getjobjid(jobs,jid);
        if(job==NULL){
            printf("%%%d:No such job\n",jid);
            return ;
        }
    }
    else if(isdigit(argv[1][0])){
        jid = atoi(argv[1]);        
        job=getjobjid(jobs,jid);
        if(job==NULL){
            printf("(%d): No such process\n",jid);
            return ;
        }

    }
    else {
        printf("%s: argument must be a PID or %%jobid\n",argv[0]);
        return ;
    }
    if(!strcmp(argv[0],"bg")){
        job->state=BG;
        kill(-(job->pid),SIGCONT);
        printf("[%d] (%d) %s", jid, job->pid, job->cmdline);  
    }
    else {
        if(job->state==BG){
            job->state=FG;
            waitfg(job->pid);
        }
        else if(job->state==ST){
            job->state=FG;
            kill(-(job->pid),SIGCONT);
            waitfg(job->pid);
        }
    }
    return;
}

/* 
 * waitfg - Block until process pid is no longer the foreground process
 */
void waitfg(pid_t pid)
{
    sigset_t mask;
    sigemptyset(&mask);
    while(pid==fgpid(jobs))sigsuspend(&mask);
    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) 
{
    pid_t pid;
    int status;
    while((pid=waitpid(-1,&status,WNOHANG|WUNTRACED))>0){      
        if(WIFEXITED(status))deletejob(jobs,pid);
        if(WIFSIGNALED(status)){
            deletejob(jobs,pid);
            printf("Job [%d] (%d) terminated by signal %d\n",pid2jid(pid),pid,WTERMSIG(status));
        }
        if(WIFSTOPPED(status)){
            struct job_t *job=getjobpid(jobs,pid);
            job->state=ST;
            printf("Job [%d] (%d) stopped by signal %d\n",pid2jid(pid),pid,WSTOPSIG(status));
        }
    }
    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) 
{
    pid_t pid=fgpid(jobs);
    kill(-pid,SIGINT);
    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) 
{
    pid_t pid=fgpid(jobs);
    kill(-pid,SIGTSTP);
    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);
}




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值