乐趣区

关于c:csapp之labshell-lab

试验目标

shell lab 次要目标是为了相熟过程管制和信号。具体来说须要比对 16 个 test 和 rtest 文件的输入,实现五个函数:

void eval(char *cmdline):剖析命令,并派生子过程执行 次要性能是解析 cmdline 并运行
int builtin_cmd(char **argv):解析和执行 bulidin 命令,包含 quit, fg, bg, and jobs
void do_bgfg(char **argv) 执行 bg 和 fg 命令
void waitfg(pid_t pid):实现阻塞期待前台程序运行完结
void sigchld_handler(int sig):SIGCHID 信号处理函数
void sigint_handler(int sig):信号处理函数,响应 SIGINT (ctrl-c) 信号 
void sigtstp_handler(int sig):信号处理函数,响应 SIGTSTP (ctrl-z) 信号

辅助函数

可用辅助函数:

  • int parseline(const char *cmdline,char **argv):获取参数列表,返回是否为后盾运行命令
  • void clearjob(struct job_t *job):革除 job 构造体。
  • 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):返回以后前台运行 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 号转化为jid
  • void listjobs(struct job_t *jobs):打印jobs
  • void sigquit_handler(int sig):解决 SIGQUIT 信号。

简介

shell 是交互式的命令行解释器,打印提示符并在 stdin 上期待输出命令,并依照命令行的内容执行。命令行是 ASCII 单词组成的命令和参数序列。若首个单词是内置命令,shell 会立刻在以后过程中执行。否则是可执行文件门路,shell 派生出子过程,而后在该子过程的上下文中加载和运行程序 。解释单个命令行而创立的子过程叫 作业 ,通常由 Unix 管道连贯的多个子过程组成。 若命令行以 & 号“&”完结,则作业将在后盾运行且不会期待作业完结。否则作业将在前台运行且期待作业终止。故在任何工夫点最多仅一个作业在前台运行。但可在后盾运行任意数量的作业。

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

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

则 argc==3,argv[0] ==‘‘/bin/ls’’,argv[1]==‘‘-l’’,argv[2]==‘‘-d’’。若在命令行后加上 &,则在后盾运行 ls 程序。shell 反对作业控制,容许用户在后盾和前台挪动作业,并更改作业中过程的状态(运行、进行或终止)。输出 ctrl- c 会向前台作业中的每个过程发送 SIGINT 信号,默认操作是终止过程。相似地,键入 ctrl- z 将向前台作业中的每个过程发送 SIGTSTP 信号,默认操作是将过程置于进行状态,直到收到 SIGCONT 信号将其唤醒。当然 shell 也提供内置命令反对作业控制:

  • jobs:列出运行和终止的后台作业
  • bg <job>:将终止的后台作业改为运行
  • fg <job>:将终止或运行的后台作业改为前台运行
  • kill <job>:发送特定信号给特定过程和过程组,默认动作是终止过程
  • quit:终止 shell

有三点值得注意:

  • tsh 不反对管道和 I / O 重定向
  • 每个作业要么被 process ID 辨认,要么被 job ID 辨认,jid 因该在命令行中用前缀“%”示意,“%5”示意 jid 5,5 示意 PID 5
  • shell 因该回收所有僵尸过程,若任何一个作业因为接管到它没有捕捉到的信号而终止,那么 tsh 应该辨认该事件,并打印 PID 和谬误形容音讯

提醒

  • 仔细阅读 CSAPP 第八章的异样控制流和 lab 的 writeup
  • make testn测试 shell 执行第 n 组测试数据的输入,make rtestn打印 shell 预期输入,tshref.out蕴含 shell 所有预期输入后果,先看文件输入,理解命令格局再编码,批改 makefile 文件中 CFLAGS 字段,加 -g 参数并去掉 -O2 参数
  • waitpid, kill, fork, execve, setpgid, sigprocmask 很罕用,可通过命令手册查看应用细节,WUNTRACEDWNOHANG 选项对 waitpid 也很有用
  • 实现信息处理函数,确保发送 SIGINTSIGTSTP信号给整个前台过程组,用 -pid 代替 pid 作为 kill 参数
  • 倡议在 waitfg 的循环中用 sleep 函数,在 sigchld_handler 中对 waitpid 只调用一次
  • eval中过程在 fork 之前用 sigprocmask 阻塞 SIGCHLD 信号,之后在解除信号阻塞,之后在调用 addjob 增加孩子到作业列表用 sigprocmask 阻塞信号,因为子继承继承父过程的阻塞汇合,所以子程序必须确保在执行新过程前解除阻塞 SIGCHLD 信号。父过程需以这种形式阻塞 SIGCHLD 信号,防止在父过程调用 addjob 之前,SIGCHLD处理器获取子过程 (从而从工作列表中删除) 的竞争状态。
  • 不要间接调用常用命令,而应输出残缺门路,如/bin/ls
  • 当在规范 Unix shell 运行 tsh 时,tsh 运行在前台过程组中。若 tsh 随后创立子过程,默认状况下,该子过程也是前台过程组的成员。因为按下 ctrl- c 会向前台组中的每个过程发送 SIGINT 信号,按下 ctrl- c 会向 tsh 及 Unix shell 创立的每个子过程,显然不正确。应该在 fork 后,但在 execve 前,子过程调用setpgid(0,0),把子过程放到新过程组中,该过程组 ID 与子过程的 PID 雷同。确保前台过程组中只有一个过程,即 tsh 过程。当按下 ctrl- c 时,tsh 应捕捉生成的 SIGINT,而后将其转发给蕴含前台作业的过程组。

试验前环境配置

因为 csapp 都是运行在 32 位零碎,即便装置 32 位零碎所需的库,依然无奈运行 tsh,在网上找到有人配置好的 csapp 的 docker 镜像,因而间接应用 docker,环境配置如下:

  1. 装置 docker,并配置减速
  2. 装置 vscode 和 ssh 插件
  3. 命令行中运行 systemctl start docker 启动 docker 和docker run --privileged -d -p 1221:22 --name shell yansongsongsong/csapp:shelllabshell lab 的试验环境
  4. 通过 ssh 输出明码登录试验环境

试验

在 vscode 中关上 shlab-handout 文件夹,并关上 tsh.c 文件,能够看到在 main 函数中调用 eval 函数,而在书 P525 或 20-ecf-sigs 的 P19 可找到 eval 函数的整体代码框架:

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,临时先不论,先搞好整体框架,实现简略的函数,到前面在思考。另外值得一提的是这里将 forkexecve都进行封装以处理错误状况。
运行 make rtest01make test01能够看到输入一样,曾经达到要求。同样操作,能够看到 test02 未依照预期退出 tsh,剖析知须要实现 builtin_cmd 函数。同样在书上 P525 能找到根底代码,只需加上jobsfgbg 3 种状况即可。代码如下:

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,通过比拟 test04rtest04的输入,确定只需批改输入格局即可:

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

接着发现 test05 是执行外部命令:jobs,打印 job list,比对rtest05 发现没有打印出 job,参考下面的提醒第 6 条,知应同步防止父子竞争,具体来说:父过程在fork 前屏蔽信号,子过程在 execve 前还原信号,因为子过程回继承原来的屏蔽信号。同时前台 job 须要调用 waitfg 进行期待。如果不阻塞会呈现子过程先完结从 jobs 中删除,而后再执行到主过程 addjob 的竞争问题。在书上 P542 和 PPT P57 页都有对应的参考代码:

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);
}

加上图中对应代码,同时若子过程完结,须要 delete job,在 sigchld_handler 中加上非阻塞循环期待子过程的代码:

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 下面被调用,而下面回调用 waitpid,因而这里不必调用只需循环期待即可
            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 中运行到此处,前端过程执行 jobs 会阻塞直到所有子过程都被回收,即两个后端过程都执行并 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;
}

如果是前台命令,则调用 waitfg 循环期待,在正文中看到最好不要用 waitpid(pid,NULL,0),其次依据下面的提醒,不要同时在sigchld_handlerwaitfg函数中应用waitpid,因为在同一个程序的两个中央都回收僵死过程,尽管也行,但容易让人蛊惑:

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

这样就实现 test05,接下来test06test07test08就是实现 SIGINTSIGSTOP信号处理函数,留神后面提醒的第 4 条用 -pid 作为 kill 的参数,同时最初一条在 forkexecve前子过程应调用 setpgid(0,0),否则回报错No such process,留神sigint_handlersigtstp_handler只需调用 kill 即可,将输入留到 sigchld_handler 中,这样就需批改后面的 sigchld_handler 以解决不同子过程退出状态:

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 中运行到此处,前端过程执行 jobs 会阻塞直到所有子过程都被回收,即两个后端过程都执行并 delete 才会来到,则 jobs 命令什么也没有打印 */
    while((pid = waitpid(-1,&status,WNOHANG | WUNTRACED))>0){
        // WNOHANG | WUNTRACED 是立刻返回
        // 用 WIFEXITED(status),WIFSIGNALED(status),WIFSTOPPED(status)等来补获终止或者
        // 被进行的子过程的退出状态。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  // 进行 只批改状态就行
        {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;  // 复原
    return;
}

这样就实现 test06test07test08。接下来 test09test10是测试 fgbg内置命令,先解析命令通过 getjobjidgetjobpid获取 job,再分状况对fgbg命令做不同解决,输出 %num 代表工作 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。接下来 test11test12test13 别离测试 Forward SIGINT Forward SIGTSTPRestart stopped process 都能失常通过,若每通过,因该是后面某些测试有问题,解决后即可。test14是测试 JIDPID的谬误输出的状况,较容易通过。test15将后面所有测试状况放一起,也顺利通过,而 test16 是测试 tsh 是否解决不是来自终端而是来自其余过程的 SIGSTPSIGINT信号,顺利通过。

总结

最终代码见下,该试验次要波及加载、过程管制、信号等根底但很重要的常识,波及到异样控制流、过程、零碎调用、信号处理函数与非本地跳转等并发编程的常识。并发的同步问题是要害,利用信号屏蔽与还原就能解决。此外浏览 man 手册理解零碎接口应用细节对实现试验很有帮忙。

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

本文由博客一文多发平台 OpenWrite 公布!

退出移动版