Added do_bgfg

main
TuDatTr 2021-02-09 22:20:23 +01:00
parent 118203244b
commit f71dad3594
1 changed files with 30 additions and 35 deletions

65
tsh.c
View File

@ -280,55 +280,50 @@ int builtin_cmd(char **argv)
*/ */
void do_bgfg(char **argv) void do_bgfg(char **argv)
{ {
struct job_t *job_1; struct job_t *job;
char *j = argv[1]; int jid;
int JID; pid_t pid;
pid_t PID;
if(j==NULL){ // if no arg // if arg empty
fprintf(stderr,"%s command requires PID or %%jobid argument\n",argv[0]); 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; return;
} }
job = getjobjid(jobs, jid);
if(job == NULL) {
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
printf("%s no such job\n", argv[1]); printf("%s no such job\n", argv[1]);
return; return;
} }
} } else { // if looking for pid
else{ // case2 process id, ex) 5 pid = atoi(argv[1]);
PID = atoi(j); if(!pid){
if(!PID){ printf("%s: argument must be a pid or %%jobid\n", argv[0]);
printf("%s: argument must be a PID or %%jobid\n", argv[0]);
return; return;
} }
job_1 = getjobpid(jobs, PID); job = getjobpid(jobs, pid);
if(job_1 == NULL){ // if non existant proc if(job == NULL){
printf("(%s) no such process\n", argv[1]); printf("(%s) no such process\n", argv[1]);
return; return;
} }
} }
PID = job_1->pid; if (job->state == ST) {
kill(-job->pid, SIGCONT); // continue process of the job
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);
} }
else{ //foreground job
job_1->state = FG; job->state = strcmp(argv[0], "fg") == 0 ? FG : BG; // set the state to the new state
kill(-PID, SIGCONT);
waitfg(job_1->pid); 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; return;
} }
@ -338,7 +333,7 @@ void do_bgfg(char **argv)
void waitfg(pid_t pid) void waitfg(pid_t pid)
{ {
while (pid == fgpid(jobs)) { while (pid == fgpid(jobs)) {
sleep(1); sleep(1); // busy loop
} }
return; return;
} }