Develop a shell in C language. Create a main() function that prints a prompt, ac
ID: 3798529 • Letter: D
Question
Develop a shell in C language.
Create a main() function that prints a prompt, accepts input, and tokenizes the input and passes the argument vector to an excuteCmd() function by using the execution int executeCMD(char**args); it will return -1 if n error is found, but a zero if not. You can exit the shell by entering an x at the prompt.
Create an executeCmd() function that can execute any program in the foreground or background as well as redirect the output of any program to a file. It will be able to execute arguments such as list files in the current directory, display directory, display number of lines or make a new directory (ls, ls -a, mkdir, wc). The program should run in the background and does not need to wait for completion before the prompt is displayed again. Output can be redirected to a file.
Explanation / Answer
//below program is used to initialize prompt, tokenize arguments , run and print array arguments
char **argv;
char argu[64]; //Global Variables
int main(int argc, char** argv)
{
mainloop(); //to call loop main for functions
return (EXIT_SUCCESS);
}
void promptsh()
{ //prompt execution
printf ("hai");
}
void mainloop()
{ //Loop to call the functions
while(1){
promptsh();
argv = (char**)malloc(sizeof(char*)*50); //allocation of memory for argv
excuteCmd(argu, argv);
if((strcmp(argv[0],"exit" )) == 0)
{
//check for exit
return 0;
}
run();
print();
}
}
void excuteCmd(char* argu, char** argv)
{
int i=0,j=0;
char c;
char* token;
while((c = getchar()) != ' ' )
{ //gets character and checks for end of line
argu[i] = c;
i++;
}
argu[i] = '';
token = strtok(argu, " ,."); //tokenize the command
while (token != NULL)
{
argv[j] = token; //passing command for argus array
token = strtok(NULL, " ,.");
j++;
}
argv[j] = NULL;
}
void run()
{ //Function to call fork and execute with errors
pid_t childpid = fork();
int retstat;
if(childpid == -1){ //if fail to fork
printf("failed to fork");
exit(1);
}
else if(childpid == 0){ //Child process
if (execvp(*argv, argv) < 0){
printf("execution error ");
exit(1);
}
else{ //sucessfully executed
printf("executed");
}
}
int c=(int)waitpid(childpid, &retstat, 0);
if (retstat == 0) // to check if child process terminated without error.
{
printf("The normal termination of child process . ");
}
if (returnStatus == 1) //to terminate with error
{
printf("The error in child process !. ");
}
}
void print() //to print the arguments
{
int i = 0;
while(argv[i] != NULL)
{
printf("Argv%d: %s ",i, argv[i] );
i++;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.