In: Computer Science
Using C Write a program that will serve as a simple shell. This shell will execute an infinite for loop. In each iteration of the loop, the user will be presented with a prompt. When the user enters a command, the shell will tokenize the command, create a child process to execute it and wait for the child process to be over. If the user enters an invalid command, the shell should recognize the situation and show a meaningful message. The shell should also provide a "quit" command that will cause the shell to terminate.
Please look at my code and in case of indentation issues check the screenshots.
-------------shell.c---------------
#include <stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<string.h>
void parseCommand(char *line, char **cmd) //splits the line into
words and stores in cmd array
{
while (*line != '\0') /* if not the end of line
....... */
{
while (*line == ' ' || *line ==
'\t' || *line == '\n')
*line++ = '\0';
/* replace white spaces with \0 */
*cmd++ = line; /* save the argument
position */
while (*line != '\0' &&
*line != ' ' && *line != '\t' && *line !=
'\n')
line++; //skip
till end of next argument
}
*cmd = '\0'; /* mark the end of argument list */
}
void executeCommand(char **argv) //calls execvp and executes the
command
{
int r = execvp(*argv, argv);
if(r < 0)
{
printf("*** ERROR: Invalid command,
exec failed\n");
exit(1);
}
}
int main (int argc, char **argv)
{
char line[1024]; /* the input line */
char *cmd[64]; /*to store the command line argument
*/
while (1)
{
int childPid;
int status;
printf("\n$myshell-> "); /*
print a prompt*/
fgets(line, sizeof(line),
stdin);
line[strlen(line)-1] = '\0';
parseCommand(line, cmd); /* parse
the line and store the words in cmd array */
if (strcmp(cmd[0], "quit") == 0)
/* is it a "quit"? */
break; /* exit
if it is */
childPid = fork(); //creates child
if (childPid == 0)
{
executeCommand(cmd); //calls execvp and executes the command
}
else
{
waitpid
(childPid, &status, 0); //waits for the child
}
}
}
--------------Screenshots--------------
--------------------Output-----------------------
--------------------------------------------------------------------------------------
Please give a thumbs up if you find this answer helpful.
If it doesn't help, please comment before giving a thumbs
down.
Please Do comment if you need any clarification.
I will surely help you.
Thankyou