diff --git a/shlab/tsh.c b/shlab/tsh.c index 8ad94d1..f25f82d 100644 --- a/shlab/tsh.c +++ b/shlab/tsh.c @@ -281,7 +281,12 @@ int builtin_cmd(char **argv) listjobs(jobs); return 1; // this IS a builtin command, return 1 to notify } - return 0; /* not a builtin command */ + if (strcmp(argv[0], "bg") == 0 || strcmp(argv[0], "fg") == 0) // judge bg & fg + { + do_bgfg(argv); + return 1; + } + return 0; /* not a builtin command */ } /* @@ -289,6 +294,59 @@ int builtin_cmd(char **argv) */ void do_bgfg(char **argv) { + char *id = argv[1], *end; // JID or PID + struct job_t *job; + int numid; + // extract job or process + if (id == NULL) // not specified + { + printf("%s command requires PID or %%jobid argument\n", argv[0]); + return; + } + if (id[0] == '%') // this is a job + { + id++; // point to the number position + numid = strtol(id, &end, 10); // convert id char[] to integer + if (*end != '\0') // contains non-digit numbers + { + printf("%s: argument must be a PID or %%jobid\n", argv[0]); + return; + } + job = getjobjid(jobs, numid); // try to get job + if (job == NULL) + { + printf("%%%d: No such job\n", numid); + return; + } + } + else // this is a process + { + numid = strtol(id, &end, 10); + if (*end != '\0') + { + printf("%s: argument must be a PID or %%jobid\n", argv[0]); + return; + } + job = getjobpid(jobs, numid); // try to get proc + if (job == NULL) + { + printf("(%d): No such process\n", atoi(id)); + return; + } + } + // send signal + kill(-(job->pid), SIGCONT); + // process according to bg/fg + if (strcmp(argv[0], "fg") == 0) // foreground + { + job->state = FG; + waitfg(job->pid); + } + else // background + { + job->state = BG; + printf("[%d] (%d) %s", job->jid, job->pid, job->cmdline); + } return; }