實驗?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
鏈表中刪除pid
的job
爪模。 -
pid_t fgpid(struct job_t *jobs)
:返回當(dāng)前前臺運行job
的pid
號欠啤。 -
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é)誊役,WUNTRACED
和WNOHANG
選項對waitpid
也很有用實現(xiàn)信息處理函數(shù)获列,確保發(fā)送
SIGINT
和SIGTSTP
信號給整個前臺進程組,用-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)境配置如下:
- 安裝docker咆蒿,并配置加速
- 安裝vscode和ssh插件
- 命令行中運行
systemctl start docker
啟動docker和docker run --privileged -d -p 1221:22 --name shell yansongsongsong/csapp:shelllab
shell lab的實驗環(huán)境 - 通過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ù),到后面在考慮别渔。另外值得一提的是這里將fork
和execve
都進行封裝以處理錯誤情況附迷。
運行make rtest01
和make test01
可以看到輸出一樣,已經(jīng)達到要求钠糊。同樣操作挟秤,可以看到test02
未按照預(yù)期退出tsh,分析知需要實現(xiàn)builtin_cmd
函數(shù)抄伍。同樣在書上P525能找到基礎(chǔ)代碼艘刚,只需加上jobs
、fg
截珍、bg
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 */
}
這樣就過了test02
和test03
箩朴,經(jīng)過比較test04
和rtest04
的輸出,確定只需修改輸出格式即可:
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_handler
和waitfg
函數(shù)中使用waitpid
润匙,因為在同一個程序的兩個地方都回收僵死進程诗眨,雖然也行,但容易讓人迷惑:
void waitfg(pid_t pid)
{
while(fgpid(jobs))
usleep(1000);//一秒
return;
}
這樣就完成test05
孕讳,接下來test06
和test07
匠楚、test08
就是實現(xiàn)SIGINT
和SIGSTOP
信號處理函數(shù),注意前面提示的第4條用-pid
作為kill的參數(shù)厂财,同時最后一條在fork
后execve
前子進程應(yīng)調(diào)用setpgid(0,0)
芋簿,否則回報錯No such process
,注意sigint_handler
和sigtstp_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;
}
這樣就完成test06
和test07
、test08
抵皱。接下來test09
和test10
是測試fg
和bg
內(nèi)置命令善榛,先解析命令通過getjobjid
或getjobpid
獲取job
,再分情況對fg
和bg
命令做不同處理叨叙,輸入%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;
}
這樣就過了test09
和test10
。接下來test11
和test12
樱蛤、test13
分別測試Forward SIGINT
钮呀、Forward SIGTSTP
、Restart stopped process
都能正常通過昨凡,若每通過爽醋,因該是前面某些測試有問題,解決后即可便脊。test14
是測試JID
或PID
的錯誤輸入的情況蚂四,較容易通過。test15
將前面所有測試情況放一起哪痰,也順利通過遂赠,而test16
是測試tsh
能否處理不是來自終端而是來自其他進程的SIGSTP
和SIGINT
信號,順利通過晌杰。
總結(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ā)布!