Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify simple-sh.c program to write simple-sh1.c program (in a loop) - (a) to ac

ID: 3857322 • Letter: M

Question

Modify simple-sh.c program to write simple-sh1.c program (in a loop) - (a) to accept a command-string (e.g., ls), (b) to fork a child process to handle the command by calling execlp where this part will replace the system call, (c) while the parent is waiting for the child to complete and then to resume the loop to accept the next command.

/*
* sh1.c: sample version 1 of a UNIX command shell/interpreter.
*
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char line[256];
char prompt[] = "SimpleShell: Enter command or exit % ";

/* spit out the prompt */
printf("%s", prompt );

/* Try getting input. If error or EOF, exit */
while( fgets(line, sizeof line, stdin) != NULL )
{
   /* fgets leaves ' ' in input buffer. ditch it */
   line[strlen(line)-1] = '';

if(strcmp(line,"exit") == 0){
break;
} else {
system( line );
}

   printf("%s", prompt );
}

return 0;
}

Explanation / Answer

Code:-

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main(){
char line[256];
char prompt[] = "SimpleShell: Enter command or exit % ";
pid_t pid;
while(1){
printf("%s", prompt );
/* Try getting input. If error or EOF, exit */
while( fgets(line, sizeof line, stdin) != NULL )
{
/* fgets leaves ' ' in input buffer. ditch it */
line[strlen(line)-1] = '';
if(strcmp(line,"exit") == 0){
exit();
}
pid = fork();
if(pid<0){
fprintf(stderr, "fork failed");
return 1; }
else if(pid == 0){
execlp(line,line, NULL);}
else{
wait(NULL);
printf("child complete ");
}
}
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote