csapp之lab:shell lab

實驗?zāi)康?/h1>

shell lab主要目的是為了熟悉進程控制和信號级乐。具體來說需要比對16個test和rtest文件的輸出阱洪,實現(xiàn)五個函數(shù):

void eval(char *cmdline):分析命令书释,并派生子進程執(zhí)行 主要功能是解析cmdline并運行
int builtin_cmd(char **argv):解析和執(zhí)行bulidin命令,包括 quit, fg, bg, and jobs
void do_bgfg(char **argv) 執(zhí)行bg和fg命令
void waitfg(pid_t pid):實現(xiàn)阻塞等待前臺程序運行結(jié)束
void sigchld_handler(int sig):SIGCHID信號處理函數(shù)
void sigint_handler(int sig):信號處理函數(shù),響應(yīng) SIGINT (ctrl-c) 信號 
void sigtstp_handler(int sig):信號處理函數(shù)圣猎,響應(yīng) SIGTSTP (ctrl-z) 信號

輔助函數(shù)

可用輔助函數(shù):

  • int parseline(const char *cmdline,char **argv):獲取參數(shù)列表,返回是否為后臺運行命令
  • void clearjob(struct job_t *job):清除job結(jié)構(gòu)體乞而。
  • void initjobs(struct job_t *jobs):初始化jobs鏈表送悔。
  • void maxjid(struct job_t *jobs):返回jobs鏈表中最大的jid號。
  • int addjob(struct job_t *jobs,pid_t pid,int state,char *cmdline):在jobs鏈表中添加job
  • int deletejob(struct job_t *jobs,pid_t pid):在jobs鏈表中刪除pidjob爪模。
  • pid_t fgpid(struct job_t *jobs):返回當(dāng)前前臺運行jobpid號欠啤。
  • struct job_t *getjobpid(struct job_t *jobs,pid_t pid):返回pid號的job
  • struct job_t *getjobjid(struct job_t *jobs,int jid):返回jid號的job屋灌。
  • int pid2jid(pid_t pid):將pid號轉(zhuǎn)化為jid洁段。
  • void listjobs(struct job_t *jobs):打印jobs
  • void sigquit_handler(int sig):處理SIGQUIT信號共郭。

簡介

shell是交互式的命令行解釋器祠丝,打印提示符并在stdin上等待輸入命令,并按照命令行的內(nèi)容執(zhí)行除嘹。命令行是ASCII單詞組成的命令和參數(shù)序列写半。若首個單詞是內(nèi)置命令,shell會立即在當(dāng)前進程中執(zhí)行尉咕。否則是可執(zhí)行文件路徑叠蝇,shell派生出子進程,然后在該子進程的上下文中加載和運行程序年缎。解釋單個命令行而創(chuàng)建的子進程叫作業(yè)悔捶,通常由Unix管道連接的多個子進程組成。若命令行以&號“&”結(jié)束晦款,則作業(yè)將在后臺運行且不會等待作業(yè)結(jié)束炎功。否則作業(yè)將在前臺運行且等待作業(yè)終止。故在任何時間點最多僅一個作業(yè)在前臺運行缓溅。但可在后臺運行任意數(shù)量的作業(yè)蛇损。

例如:tsh> /bin/ls -l -d

在前臺運行程序,程序的入口是:int main(int argc,char *argv[])

則argc==3坛怪,argv[0] == ‘‘/bin/ls’’淤齐,argv[1]== ‘‘-l’’,argv[2]== ‘‘-d’’。若在命令行后加上&袜匿,則在后臺運行l(wèi)s程序更啄。shell支持作業(yè)控制,允許用戶在后臺和前臺移動作業(yè)居灯,并更改作業(yè)中進程的狀態(tài)(運行祭务、停止或終止)内狗。輸入ctrl-c會向前臺作業(yè)中的每個進程發(fā)送SIGINT信號,默認(rèn)操作是終止進程义锥。類似地柳沙,鍵入ctrl-z將向前臺作業(yè)中的每個進程發(fā)送SIGTSTP信號,默認(rèn)操作是將進程置于停止?fàn)顟B(tài)拌倍,直到收到SIGCONT信號將其喚醒赂鲤。當(dāng)然shell也提供內(nèi)置命令支持作業(yè)控制:

  • jobs:列出運行和終止的后臺作業(yè)
  • bg <job>:將終止的后臺作業(yè)改為運行
  • fg <job>:將終止或運行的后臺作業(yè)改為前臺運行
  • kill <job>:發(fā)送特定信號給特定進程和進程組,默認(rèn)動作是終止進程
  • quit:終止shell

有三點值得注意:

  • tsh不支持管道和I/O重定向
  • 每個作業(yè)要么被process ID識別柱恤,要么被job ID識別数初,jid因該在命令行中用前綴“%”表示,“%5”表示jid 5梗顺,5表示PID 5
  • shell因該回收所有僵尸進程泡孩,若任何一個作業(yè)因為接收到它沒有捕捉到的信號而終止,那么tsh應(yīng)該識別該事件荚守,并打印PID和錯誤描述消息

提示

  • 仔細(xì)閱讀CSAPP第八章的異痴涞拢控制流和lab的writeup

  • make testn測試shell執(zhí)行第n組測試數(shù)據(jù)的輸出,make rtestn打印shell預(yù)期輸出矗漾,tshref.out包含shell所有預(yù)期輸出結(jié)果锈候,先看文件輸出,了解命令格式再編碼敞贡,修改makefile文件中CFLAGS字段泵琳,加-g參數(shù)并去掉-O2參數(shù)

  • waitpid, kill, fork,execve, setpgid, sigprocmask 很常用,可通過命令手冊查看使用細(xì)節(jié)誊役,WUNTRACEDWNOHANG選項對waitpid也很有用

  • 實現(xiàn)信息處理函數(shù)获列,確保發(fā)送SIGINTSIGTSTP信號給整個前臺進程組,用-pid代替pid作為kill參數(shù)

  • 建議在waitfg的循環(huán)中用sleep函數(shù)蛔垢,在sigchld_handler中對waitpid只調(diào)用一次

  • eval中進程在fork之前用sigprocmask阻塞SIGCHLD信號击孩,之后在解除信號阻塞,之后在調(diào)用addjob添加孩子到作業(yè)列表用sigprocmask阻塞信號鹏漆,因為子繼承繼承父進程的阻塞集合巩梢,所以子程序必須確保在執(zhí)行新進程前解除阻塞SIGCHLD信號。父進程需以這種方式阻塞SIGCHLD信號艺玲,避免在父進程調(diào)用addjob之前括蝠,SIGCHLD處理器獲取子進程(從而從任務(wù)列表中刪除)的競爭狀態(tài)。

  • 不要直接調(diào)用常用命令饭聚,而應(yīng)輸入完整路徑忌警,如/bin/ls

  • 當(dāng)在標(biāo)準(zhǔn)Unix shell運行tsh時,tsh運行在前臺進程組中秒梳。若tsh隨后創(chuàng)建子進程法绵,默認(rèn)情況下箕速,該子進程也是前臺進程組的成員。因為按下ctrl-c會向前臺組中的每個進程發(fā)送SIGINT信號礼烈,按下ctrl-c會向tsh及Unix shell創(chuàng)建的每個子進程弧满,顯然不正確婆跑。應(yīng)該在fork后此熬,但在execve前,子進程調(diào)用setpgid(0,0)滑进,把子進程放到新進程組中犀忱,該進程組ID與子進程的PID相同。確保前臺進程組中只有一個進程扶关,即tsh進程阴汇。當(dāng)按下ctrl-c時,tsh應(yīng)捕獲生成的SIGINT节槐,然后將其轉(zhuǎn)發(fā)給包含前臺作業(yè)的進程組搀庶。

實驗前環(huán)境配置

由于csapp都是運行在32位系統(tǒng),即使安裝32位系統(tǒng)所需的庫铜异,仍然無法運行tsh哥倔,在網(wǎng)上找到有人配置好的csapp的docker鏡像,因此直接使用docker揍庄,環(huán)境配置如下:

  1. 安裝docker咆蒿,并配置加速
  2. 安裝vscode和ssh插件
  3. 命令行中運行systemctl start docker啟動docker和docker run --privileged -d -p 1221:22 --name shell yansongsongsong/csapp:shelllabshell lab的實驗環(huán)境
  4. 通過ssh輸入密碼登錄實驗環(huán)境

實驗

在vscode中打開shlab-handout文件夾,并打開tsh.c文件蚂子,可以看到在main函數(shù)中調(diào)用eval函數(shù)沃测,而在書P525或20-ecf-sigs的P19可找到eval函數(shù)的整體代碼框架:

void eval(char *cmdline) 
{
    char *argv[MAXARGS];/*Argument list execve() */
    char buf[MAXLINE];/*Holds modified command line */
    int bg;/*Should the job run in bg or fg? */
    pid_t pid;/*Process id */

    strcpy(buf, cmdline);
    bg = parseline(buf, argv);
    if (argv[0] == NULL)
        return;/* Ignore empty lines */

    if (!builtin_cmd(argv)) {
        if ((pid = Fork()) == 0) {/* Child runs user job */
            Execve(argv[0], argv, environ);
        }/* Parent waits for foreground job to terminate */
        if (!bg) {
            int status;
            if (waitpid(pid, &status,0) < 0)
                unix_error("waitfg: waitpid error");
        }
        else
            printf("%d %s", pid, cmdline);
    }
    return;
}

盡管ppt上說有bug,暫時先不管食茎,先搞好整體框架蒂破,完成簡單的函數(shù),到后面在考慮别渔。另外值得一提的是這里將forkexecve都進行封裝以處理錯誤情況附迷。
運行make rtest01make test01可以看到輸出一樣,已經(jīng)達到要求钠糊。同樣操作挟秤,可以看到test02未按照預(yù)期退出tsh,分析知需要實現(xiàn)builtin_cmd函數(shù)抄伍。同樣在書上P525能找到基礎(chǔ)代碼艘刚,只需加上jobsfg截珍、bg3種情況即可攀甚。代碼如下:

int builtin_cmd(char **argv) 
{
    if(!strcmp(argv[0],"quit")) /* quit command */
        exit(0);

    if (!strcmp(argv[0], "&")) /* Ignore singleton & */
        return 1; 
    
    if(!strcmp((argv[0]),"jobs"))/* jobs command */
    {
        listjobs(jobs);
        return 1;
    }

    if(!strcmp((argv[0]),"fg") || !strcmp((argv[0]),"bg"))/* bg/fg command */
    {
        do_bgfg(argv);
        return 1;
    }
    return 0;     /* not a builtin command */
}

這樣就過了test02test03箩朴,經(jīng)過比較test04rtest04的輸出,確定只需修改輸出格式即可:

printf("[%d] (%d) %s", pid2jid(pid),pid, cmdline);

接著發(fā)現(xiàn)test05是執(zhí)行內(nèi)部命令:jobs秋度,打印job list炸庞,比對rtest05發(fā)現(xiàn)沒有打印出job,參考上面的提示第6條荚斯,知應(yīng)同步避免父子競爭埠居,具體來說:父進程在fork前屏蔽信號,子進程在execve前還原信號事期,因為子進程回繼承原來的屏蔽信號滥壕。同時前臺job需要調(diào)用waitfg進行等待。如果不阻塞會出現(xiàn)子進程先結(jié)束從jobs中刪除兽泣,然后再執(zhí)行到主進程addjob的競爭問題绎橘。在書上P542和PPT P57頁都有對應(yīng)的參考代碼:

int main(int argc, char **argv)
{
    int pid;
    sigset_t mask_all, mask_one, prev_one;
    int n = N; /* N = 5 */
    Sigfillset(&mask_all);
    Sigemptyset(&mask_one);
    Sigaddset(&mask_one, SIGCHLD);
    Signal(SIGCHLD, handler);
    initjobs(); /* Initialize the job list */
    
    while (n--) {
        Sigprocmask(SIG_BLOCK, &mask_one, &prev_one); /* Block SIGCHLD */
        if ((pid = Fork()) == 0) { /* Child process */
            Sigprocmask(SIG_SETMASK, &prev_one, NULL); /* Unblock SIGCHLD */
            Execve("/bin/date", argv, NULL);
        }
        Sigprocmask(SIG_BLOCK, &mask_all, NULL); /* Parent process */
        addjob(pid); /* Add the child to the job list */
        Sigprocmask(SIG_SETMASK, &prev_one, NULL); /* Unblock SIGCHLD */
    }
    exit(0);
}

加上圖中對應(yīng)代碼,同時若子進程結(jié)束唠倦,需要delete job称鳞,在sigchld_handler中加上非阻塞循環(huán)等待子進程的代碼:

void eval(char *cmdline) 
{
    char *argv[MAXARGS];/*Argument list execve() */
    char buf[MAXLINE];/*Holds modified command line */
    int bg;/*Should the job run in bg or fg? */
    pid_t pid;/*Process id */
    sigset_t mask_all,mask_one,prev_one;

    strcpy(buf, cmdline);
    bg = parseline(buf, argv);
    if (argv[0] == NULL)
        return;/* Ignore empty lines */

    if (!builtin_cmd(argv)) {
        Sigfillset(&mask_all);/* add every signal number to set */
        Sigemptyset(&mask_one);/* create empty set */
        Sigaddset(&mask_one, SIGCHLD);/* add signal number to set */

        /*  block SIGINT and save previous blocked set */
        Sigprocmask(SIG_BLOCK, &mask_one, &prev_one); /* Block SIGCHLD */
        if ((pid = Fork()) == 0) {/* Child runs user job */
            /* restore previous blocked set,unblocking SIGINT */
            Sigprocmask(SIG_SETMASK, &prev_one, NULL); /* Unblock SIGCHLD */
            //Setpgid(0,0);
            Execve(argv[0], argv, environ);
        }/* Parent waits for foreground job to terminate */

        Sigprocmask(SIG_BLOCK, &mask_all, NULL); /* Block SIGCHLD */
        int st = (bg==0) ? FG : BG;
        addjob(jobs,pid,st,cmdline);
        Sigprocmask(SIG_SETMASK, &prev_one, NULL); /* Unblock SIGCHLD */
        if (!bg) {
            //由于sigchld_handler上面被調(diào)用,而上面回調(diào)用waitpid稠鼻,因此這里不用調(diào)用只需循環(huán)等待即可
            waitfg(pid);
        }
        else
            printf("[%d] (%d) %s", pid2jid(pid),pid, cmdline);
    }
    return;
}
void sigchld_handler(int sig) 
{
    int olderrno = errno;
    sigset_t mask_all,prev_all;
    pid_t pid;
    Sigfillset(&mask_all);
    /*改成非阻塞冈止,否則test05中運行到此處,前端進程執(zhí)行jobs會阻塞直到所有子進程都被回收枷餐,即兩個后端進程都執(zhí)行并delete才會離開靶瘸,則jobs命令什么也沒有打印*/
    while((pid = waitpid(-1,NULL,WNOHANG | WUNTRACED))>0){
        Sigprocmask(SIG_BLOCK,&mask_all,&prev_all);
        deletejob(jobs,pid);
        Sigprocmask(SIG_SETMASK,&prev_all,NULL);
    }
    errno = olderrno;
    return;
}

如果是前臺命令,則調(diào)用waitfg循環(huán)等待毛肋,在注釋中看到最好不要用waitpid(pid,NULL,0)怨咪,其次根據(jù)上面的提示,不要同時在sigchld_handlerwaitfg函數(shù)中使用waitpid润匙,因為在同一個程序的兩個地方都回收僵死進程诗眨,雖然也行,但容易讓人迷惑:

void waitfg(pid_t pid)
{
    while(fgpid(jobs))
        usleep(1000);//一秒
    return;
}

這樣就完成test05孕讳,接下來test06test07匠楚、test08就是實現(xiàn)SIGINTSIGSTOP信號處理函數(shù),注意前面提示的第4條用-pid作為kill的參數(shù)厂财,同時最后一條在forkexecve前子進程應(yīng)調(diào)用setpgid(0,0)芋簿,否則回報錯No such process,注意sigint_handlersigtstp_handler只需調(diào)用kill即可璃饱,將輸出留到sigchld_handler中与斤,這樣就需修改前面的sigchld_handler以處理不同子進程退出狀態(tài):

void sigint_handler(int sig) 
{
    int olderrno = errno;
    pid_t fg = fgpid(jobs);
    if(fg){
        Kill(-fg,sig);
    }
    errno = olderrno;
    return;
}
void sigtstp_handler(int sig) 
{
    int olderrno = errno;
    pid_t fg = fgpid(jobs);
    if(fg){
        Kill(-fg,sig);
    }
    errno = olderrno;
    return;
}
void sigchld_handler(int sig) 
{
    int olderrno = errno;
    sigset_t mask_all,prev;
    pid_t pid;
    int status;
    Sigfillset(&mask_all);
    /*改成非阻塞,否則test05中運行到此處,前端進程執(zhí)行jobs會阻塞直到所有子進程都被回收撩穿,即兩個后端進程都執(zhí)行并delete才會離開磷支,則jobs命令什么也沒有打印*/
    while((pid = waitpid(-1,&status,WNOHANG | WUNTRACED))>0){
        // WNOHANG | WUNTRACED 是立即返回
        // 用WIFEXITED(status),WIFSIGNALED(status)食寡,WIFSTOPPED(status)等來補獲終止或者
        // 被停止的子進程的退出狀態(tài)雾狈。
        if (WIFEXITED(status))  // 正常退出 delete
        {
            sigprocmask(SIG_BLOCK, &mask_all, &prev);
            deletejob(jobs, pid);
            sigprocmask(SIG_SETMASK, &prev, NULL);
        }
        else if (WIFSIGNALED(status))  // 信號退出 delete
        {
            struct job_t* job = getjobpid(jobs, pid);
            sigprocmask(SIG_BLOCK, &mask_all, &prev);
            printf("Job [%d] (%d) terminated by signal %d\n", job->jid, job->pid, WTERMSIG(status));
            deletejob(jobs, pid);
            sigprocmask(SIG_SETMASK, &prev, NULL);
        }
        else  // 停止 只修改狀態(tài)就行
        {
            struct job_t* job = getjobpid(jobs, pid);
            sigprocmask(SIG_BLOCK, &mask_all, &prev);
            printf("Job [%d] (%d) stopped by signal %d\n", job->jid, job->pid, WSTOPSIG(status));
            job->state= ST;
            sigprocmask(SIG_SETMASK, &prev, NULL);
        }
    }
    errno = olderrno;  // 恢復(fù)
    return;
}

這樣就完成test06test07test08抵皱。接下來test09test10是測試fgbg內(nèi)置命令善榛,先解析命令通過getjobjidgetjobpid獲取job,再分情況對fgbg命令做不同處理叨叙,輸入%num 代表任務(wù)id锭弊,num代表進程id,分情況討論即可擂错,但要注意各種異常情況:

void do_bgfg(char **argv) 
{
    if(!argv[1]){
        printf("%s command requires PID or %%jobid argument\n", argv[0]);
        return;
    }

    if (!isdigit(argv[1][0]) && argv[1][0] != '%') {            // Checks if the second argument is valid
        printf("%s: argument must be a PID or %%jobid\n", argv[0]);
        return;
    }

    struct job_t* myjob;
    if(argv[1][0]=='%'){
        myjob = getjobjid(jobs,atoi(&argv[1][1]));
        if(!myjob){
            printf("%s: No such job\n", argv[1]);
            return;
        }
    }else{
        myjob = getjobpid(jobs,atoi(argv[1]));
        if (!myjob) {                                 // Checks if the given PID is there
            printf("(%d): No such process\n", atoi(argv[1]));
            return;
        }
    }

    Kill(-myjob->pid,SIGCONT);
    if(!strcmp(argv[0],"bg")){
        myjob->state = BG;
        printf("[%d] (%d) %s",myjob->jid,myjob->pid,myjob->cmdline);
    }else{
        myjob->state = FG;
        waitfg(myjob->pid);
    }

    return;
}

這樣就過了test09test10。接下來test11test12 樱蛤、test13分別測試Forward SIGINT钮呀、Forward SIGTSTPRestart stopped process都能正常通過昨凡,若每通過爽醋,因該是前面某些測試有問題,解決后即可便脊。test14是測試JIDPID的錯誤輸入的情況蚂四,較容易通過。test15將前面所有測試情況放一起哪痰,也順利通過遂赠,而test16是測試tsh能否處理不是來自終端而是來自其他進程的SIGSTPSIGINT信號,順利通過晌杰。

總結(jié)

最終代碼見下跷睦,該實驗主要涉及加載、進程控制肋演、信號等基礎(chǔ)但很重要的知識抑诸,涉及到異常控制流爹殊、進程蜕乡、系統(tǒng)調(diào)用、信號處理函數(shù)與非本地跳轉(zhuǎn)等并發(fā)編程的知識。并發(fā)的同步問題是關(guān)鍵挑胸,利用信號屏蔽與還原就能解決狠角。此外閱讀 man 手冊了解系統(tǒng)接口使用細(xì)節(jié)對完成實驗很有幫助巴碗。

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

/*error handling function */
pid_t Fork(void);
void Execve(const char *filename, char *const argv[], char *const environ[]);
void Kill(pid_t pid, int signum);
void Sigemptyset(sigset_t *set);
void Sigaddset(sigset_t *set, int signum);
void Sigfillset(sigset_t *set);
void Setpgid(pid_t pid, pid_t pgid);
void Sigprocmask(int how, sigset_t *set, sigset_t *oldset);
/* 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];/*Argument list execve() */
    char buf[MAXLINE];/*Holds modified command line */
    int bg;/*Should the job run in bg or fg? */
    pid_t pid;/*Process id */
    sigset_t mask_all,mask_one,prev_one;

    strcpy(buf, cmdline);
    bg = parseline(buf, argv);
    if (argv[0] == NULL)
        return;/* Ignore empty lines */

    if (!builtin_cmd(argv)) {
        //blocking SIGCHLD in if status,otherewise it maybe has bugs
        Sigfillset(&mask_all);/* add every signal number to set */
        Sigemptyset(&mask_one);/* create empty set */
        Sigaddset(&mask_one, SIGCHLD);/* add signal number to set */

        /*  block SIGINT and save previous blocked set */
        /* avoid parent process run to addjob exited,before fork child process block sigchild signal,after call addjob unblock  */
        Sigprocmask(SIG_BLOCK, &mask_one, &prev_one); /* Block SIGCHLD */
        if ((pid = Fork()) == 0) {/* Child runs user job */
            /* restore previous blocked set,unblocking SIGINT */
            /* child process inherit parent process' blocking sets,avoid it can't receive itself child process signal,so we must unblock */
            Sigprocmask(SIG_SETMASK, &prev_one, NULL); /* Unblock SIGCHLD */
            Setpgid(0,0);// set child's group to a new process group (this is identical to the child's PID)
            Execve(argv[0], argv, environ);//this function not return ,so must call exit,otherewise it will run forever
        }/* Parent waits for foreground job to terminate */

        Sigprocmask(SIG_BLOCK, &mask_all, NULL); /* Block SIGCHLD */
        int st = (bg==0) ? FG : BG;
        addjob(jobs,pid,st,cmdline);
        Sigprocmask(SIG_SETMASK, &prev_one, NULL); /* Unblock SIGCHLD */
        if (!bg) {
            //because sigchld_handler was called above称簿,it call waitpid扣癣,so don't call and circular wait wait
            waitfg(pid);
        }
        else
            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")) /* quit command */
        exit(0);

    if (!strcmp(argv[0], "&")) /* Ignore singleton & */
        return 1; 
    
    if(!strcmp((argv[0]),"jobs"))/* jobs command */
    {
        listjobs(jobs);
        return 1;
    }

    if(!strcmp((argv[0]),"fg") || !strcmp((argv[0]),"bg"))/* bg/fg command */
    {
        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) 
{
    if(!argv[1]){
        printf("%s command requires PID or %%jobid argument\n", argv[0]);
        return;
    }

    if (!isdigit(argv[1][0]) && argv[1][0] != '%') {            // Checks if the second argument is valid
        printf("%s: argument must be a PID or %%jobid\n", argv[0]);
        return;
    }

    struct job_t* myjob;
    if(argv[1][0]=='%'){//jid
        myjob = getjobjid(jobs,atoi(&argv[1][1]));
        if(!myjob){
            printf("%s: No such job\n", argv[1]);
            return;
        }
    }else{//pid
        myjob = getjobpid(jobs,atoi(argv[1]));
        if (!myjob) {                                 // Checks if the given PID is there
            printf("(%d): No such process\n", atoi(argv[1]));
            return;
        }
    }

    Kill(-myjob->pid,SIGCONT);//send continue signal 
    if(!strcmp(argv[0],"bg")){
        myjob->state = BG;
        printf("[%d] (%d) %s",myjob->jid,myjob->pid,myjob->cmdline);
    }else{
        myjob->state = FG;
        waitfg(myjob->pid);
    }

    return;
}

/* 
 * waitfg - Block until process pid is no longer the foreground process
 */
void waitfg(pid_t pid)
{
    while(fgpid(jobs))
        usleep(1000);//sleep one second
    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;
    sigset_t mask_all,prev;
    pid_t pid;
    int status;
    Sigfillset(&mask_all);
    while((pid = waitpid(-1,&status,WNOHANG | WUNTRACED))>0){
        // WNOHANG | WUNTRACED return immediately
        if (WIFEXITED(status))  // normally exited,delete job
        {
            sigprocmask(SIG_BLOCK, &mask_all, &prev);
            deletejob(jobs, pid);
            sigprocmask(SIG_SETMASK, &prev, NULL);
        }
        else if (WIFSIGNALED(status))  //terminated by signal, delete job and print message
        {
            struct job_t* job = getjobpid(jobs, pid);
            sigprocmask(SIG_BLOCK, &mask_all, &prev);
            printf("Job [%d] (%d) terminated by signal %d\n", job->jid, job->pid, WTERMSIG(status));
            deletejob(jobs, pid);
            sigprocmask(SIG_SETMASK, &prev, NULL);
        }
        else  //stopped,change the status
        {
            struct job_t* job = getjobpid(jobs, pid);
            sigprocmask(SIG_BLOCK, &mask_all, &prev);
            printf("Job [%d] (%d) stopped by signal %d\n", job->jid, job->pid, WSTOPSIG(status));
            job->state= ST;
            sigprocmask(SIG_SETMASK, &prev, NULL);
        }
        //actually there is WIFCONTINUED,but we don't care about
    }
    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 fg = fgpid(jobs);
    if(fg){
        Kill(-fg,sig);
    }
    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 fg = fgpid(jobs);
    if(fg){
        Kill(-fg,sig);
    }
    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);
}

/******************************
 * my functions with error handling
 ******************************/

/*
 * fork error handling
 */
pid_t Fork(void)
{
    pid_t pid;

    if ((pid = fork()) < 0)
        unix_error("Fork error");
    return pid;
}

/*
 * execve error handling
 */
void Execve(const char *filename, char *const argv[], char *const environ[])
{
    if (execve(filename, argv, environ) < 0) {
        printf("%s: Command not found.\n", argv[0]);
        exit(0);
    }
}

/*
 * kill error handling
 */
void Kill(pid_t pid, int signum) 
{
    int kr;

    if ((kr = kill(pid, signum)) < 0)
        unix_error("Kill error");
    return;
}

/*
 * sigemptyset error handling
 */
void Sigemptyset(sigset_t *set)
{
    if(sigemptyset(set)<0)
        unix_error("Sigemptyset error");
    return;
}
/*
 * sigaddset error handling
 */
void Sigaddset(sigset_t *set,int sign)
{
    if(sigaddset(set,sign)<0)
        unix_error("Sigaddset error");
    return;
}

/*
 * sigprocmask error handling
 */ 
void Sigprocmask(int how, sigset_t *set, sigset_t *oldset)
{
    if(sigprocmask(how,set,oldset)<0)
        unix_error("Sigprocmask error");
    return;
}

/*
 * sigfillset error handling
 */
void Sigfillset(sigset_t *set)
{
    if(sigfillset(set)<0)
        unix_error("Sigfillset error");
    return;
}

/*
 * setpgid error handling
 */
void Setpgid(pid_t pid, pid_t pgid) {
    int rc;

    if ((rc = setpgid(pid, pgid)) < 0)
        unix_error("Setpgid error");
    return;
}

本文由博客一文多發(fā)平臺 OpenWrite 發(fā)布!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末憨降,一起剝皮案震驚了整個濱河市父虑,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌授药,老刑警劉巖士嚎,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異悔叽,居然都是意外死亡莱衩,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進店門娇澎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來笨蚁,“玉大人,你說我怎么就攤上這事趟庄±ㄏ福” “怎么了?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵戚啥,是天一觀的道長奋单。 經(jīng)常有香客問我,道長猫十,這世上最難降的妖魔是什么览濒? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮拖云,結(jié)果婚禮上贷笛,老公的妹妹穿的比我還像新娘。我一直安慰自己江兢,他們只是感情好昨忆,可當(dāng)我...
    茶點故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著杉允,像睡著了一般邑贴。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上叔磷,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天拢驾,我揣著相機與錄音,去河邊找鬼改基。 笑死繁疤,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播稠腊,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼躁染,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了架忌?” 一聲冷哼從身側(cè)響起吞彤,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎叹放,沒想到半個月后饰恕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡井仰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年埋嵌,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片俱恶。...
    茶點故事閱讀 40,115評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡雹嗦,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出速那,到底是詐尸還是另有隱情俐银,我是刑警寧澤,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布端仰,位于F島的核電站,受9級特大地震影響田藐,放射性物質(zhì)發(fā)生泄漏荔烧。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一汽久、第九天 我趴在偏房一處隱蔽的房頂上張望鹤竭。 院中可真熱鬧,春花似錦景醇、人聲如沸臀稚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽吧寺。三九已至,卻和暖如春散劫,著一層夾襖步出監(jiān)牢的瞬間稚机,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工获搏, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留赖条,地道東北人。 一個月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像纬乍,于是被迫代替她去往敵國和親碱茁。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,055評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 原文鏈接 目標(biāo) 補全tsh.c中剩余的代碼: void eval(char *cmdline):解析并執(zhí)行命令仿贬。 ...
    Coc0閱讀 978評論 0 0
  • 一步一步教你寫SHELL 這個LAB 是上完CMU CSAPP的14-15 LECTURE之后纽竣,就可以做了。csa...
    西部小籠包閱讀 9,349評論 1 5
  • 一步一步教你寫SHELL 這個LAB 是上完CMU CSAPP的14-15 LECTURE之后诅蝶,就可以做了退个。csa...
    西部小籠包閱讀 415評論 0 1
  • 實驗介紹 完成一個簡單的shell程序,總體的框架和輔助代碼都已經(jīng)提供好了调炬,我們需要完成的函數(shù)主要以下幾個: ev...
    leon4ever閱讀 8,389評論 1 4
  • 實驗之前 這個實驗難度比較適中语盈,當(dāng)然前提是你第八章認(rèn)真研究過了幾遍,在做這個實驗之前缰泡,請必須閱讀以便官網(wǎng)的writ...
    我是真ikun閱讀 4,054評論 1 2