Added do_bgfg
parent
118203244b
commit
f71dad3594
65
tsh.c
65
tsh.c
|
@ -280,55 +280,50 @@ int builtin_cmd(char **argv)
|
|||
*/
|
||||
void do_bgfg(char **argv)
|
||||
{
|
||||
struct job_t *job_1;
|
||||
char *j = argv[1];
|
||||
int JID;
|
||||
pid_t PID;
|
||||
struct job_t *job;
|
||||
int jid;
|
||||
pid_t pid;
|
||||
|
||||
if(j==NULL){ // if no arg
|
||||
fprintf(stderr,"%s command requires PID or %%jobid argument\n",argv[0]);
|
||||
// if arg empty
|
||||
if(argv[1]==NULL){
|
||||
fprintf(stderr,"%s command requires pid or %%jobid argument\n",argv[0]);
|
||||
return;
|
||||
} else if(argv[1][0] == '%') { // if looking for jid
|
||||
jid = atoi(&argv[1][1]);
|
||||
if(!jid){
|
||||
printf("%s: argument must be a pid or %%jobid\n", argv[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
else if(j[0] == '%'){ // case1 job id , ex) %5
|
||||
JID = atoi(&j[1]);
|
||||
if(!JID){
|
||||
printf("%s: argument must be a PID or %%jobid\n", argv[0]);
|
||||
return;
|
||||
}
|
||||
job_1 = getjobjid(jobs, JID);
|
||||
if(job_1 == NULL){ // if not existing job
|
||||
job = getjobjid(jobs, jid);
|
||||
if(job == NULL) {
|
||||
printf("%s no such job\n", argv[1]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else{ // case2 process id, ex) 5
|
||||
PID = atoi(j);
|
||||
if(!PID){
|
||||
printf("%s: argument must be a PID or %%jobid\n", argv[0]);
|
||||
} else { // if looking for pid
|
||||
pid = atoi(argv[1]);
|
||||
if(!pid){
|
||||
printf("%s: argument must be a pid or %%jobid\n", argv[0]);
|
||||
return;
|
||||
}
|
||||
job_1 = getjobpid(jobs, PID);
|
||||
if(job_1 == NULL){ // if non existant proc
|
||||
job = getjobpid(jobs, pid);
|
||||
if(job == NULL){
|
||||
printf("(%s) no such process\n", argv[1]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
PID = job_1->pid;
|
||||
|
||||
if(!strcmp("bg", argv[0])){ //background job
|
||||
job_1->state = BG;
|
||||
printf("[%d] (%d) %s", job_1->jid, job_1->pid, job_1->cmdline);
|
||||
kill(-PID, SIGCONT);
|
||||
|
||||
if (job->state == ST) {
|
||||
kill(-job->pid, SIGCONT); // continue process of the job
|
||||
}
|
||||
else{ //foreground job
|
||||
job_1->state = FG;
|
||||
kill(-PID, SIGCONT);
|
||||
waitfg(job_1->pid);
|
||||
|
||||
job->state = strcmp(argv[0], "fg") == 0 ? FG : BG; // set the state to the new state
|
||||
|
||||
if (job->state == FG) {
|
||||
waitfg(job->pid); // if foreground, wait for the foreground job
|
||||
} else {
|
||||
printf("[%d] (%d) %s", job->jid, job->pid, job->cmdline);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -338,7 +333,7 @@ void do_bgfg(char **argv)
|
|||
void waitfg(pid_t pid)
|
||||
{
|
||||
while (pid == fgpid(jobs)) {
|
||||
sleep(1);
|
||||
sleep(1); // busy loop
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue