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

Help in UNIX bash Modify simple-sh.c program to write simple-sh1.c program (in a

ID: 3725452 • Letter: H

Question

Help in UNIX bash

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.

#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;

}