Question: Could someone help me with my code in C? The basic problem is to design and implement a basic shell interface that supports the execution
Could someone help me with my code in C?
The basic problem is to design and implement a basic shell interface that supports the execution of other programs and a series of built-in functions.
I am having trouble with this part - Once the shell understands what commands to execute it is time to implement the execution of simple commands. Since the execution of another program involves creating another process, you will have to use the fork() system call to create another process. Once you have created the new child process, that process must use the execvp() system call to execute the program. Finally, the parent (shell) process must wait for the child process to complete before releasing the childs resources using the waitpid() system call. However, the execvp() system call may return if there is an error. If it does, your shell should print an error, reset, and prompt for new input.
Not all commands are actually programs, and your shell must implement two built-in commands. In other words, if you encounter any of these two commands, do not execute them using fork(), exec(), and waitpid(). Instead, your shell should call a subroutine that implements the following functionality.: exit-quits, cd[PATH] - Changes the present working directory, and showpid -shows the last 5 child process IDs created by your shell
Here is my code so far:
#include #include #include #include #include
#define MAX_LINE 80
int main() { char str[100]; char *p; char *args[MAX_LINE/2+1]; int count=0,pid,i; printf("$ "); fgets(str, 120, stdin); while(strcmp(str, "exit ")!=0) { if(strcmp(str,"help ") == 0) { printf("enter Linux commands, or exit to exit "); printf("$ "); }
else { //fgets(str, 1000, stdin); printf("$ "); count=0; //fgets(buff,sizeof(buff),stdin); //eliminate /n in buff str[strlen(str)-1]='\0'; //printf("%s ",buff); //alocate memory for 10 array of strings for(i = 0; i < 10; i++) { args[i] = (char*)malloc(20*sizeof(char)); } //now make a argument list and add to string array p=strtok(str," "); if(p == NULL) break; strcpy(args[count++],p); } //after building list of commands , execute command using execvp , for that create child process args[count]=NULL; pid = fork(); if(strcmp(str,"exit") == 0) { exit(0); } //child process if(pid == 0) { //execvp(args[0],args); if(strcmp(str,"help") == 0) { exit(0); } execvp(args[0],args); perror("ps error: "); printf("After execvp failed "); exit(0); } //Parent process else { //wait for chidl to finish wait(0); //printf("Finished executing user command %s ",buff); if(strcmp(str,"exit") == 0) { exit(0); } str[0]='\0'; count=0; *args=NULL; } }
fflush(stdin); fgets(str, 1000, stdin); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
