(Write the code in C, not C++) Write a simple shell (command interpreter), which
ID: 3811249 • Letter: #
Question
(Write the code in C, not C++)
Write a simple shell (command interpreter), which reads commands from the standard input and executes them. Here are the features that must be included in your program: Display the prompt "" before reading the next command line. Read and parse one command line at a time from the standard input. You can assume that only one command and its arguments are in a command line. The command "exit" should cause your program to terminate. Call fork() to create a new process, which calls one of the exec functions to execute the command that was read. Your program should wait until the execution of the command is finished and then continue to read the next command line.Explanation / Answer
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <sys/types.h>
#include <fstream>
#include <sys/time.h>
#define BUFFER_LENGTH 1024
using namespace std;
int main(){
char line[BUFFER_LENGTH];
char* argv[100];
char* path= "/bin/";
char execmd[20];
int arguments;
while(1){
printf("My shell>> ");
if(!fgets(line, BUFFER_LENGTH, stdin)){
size_t length = strlen(line);
if (line[length - 1] == ' ')
line[length - 1] = '';
}
if(strcmp(line, "exit")==0){
break;
}
char *token;
token = strtok(line," ");
int i=0;
while(token!=NULL){
argv[i]=token;
token = strtok(NULL," ");
i++;
}
argv[i]=NULL;
arguments=i;
for(i=0; i<arguments; i++){
printf("%s ", argv[i]);
}
strcpy(execmd, path);
strcat(execmd, argv[0]);
for(i=0; i<strlen(execmd); i++){
if(execmd[i]==' '){
execmd[i]='';
}
}
int pid = fork();
if(pid==0){
execvp(execmd,argv);
fprintf(stderr, "Child process could not do execvp ");
}else{
wait(NULL);
printf("Child exited ");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.