Commit 23a7f629 authored by Mohamad Bashar Desoki's avatar Mohamad Bashar Desoki

Mini shell code

parents
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX 60
// Read a line from stdin
char *readcommand(){
char *line = (char*) malloc(sizeof(char) * MAX);
printf("$> ");
fgets(line, MAX, stdin);
size_t ln = strlen(line)-1;
if (line[ln] == '\n')
line[ln] = '\0';
return line;
}
// Split the line into tokens
char **splitcommand(char *line){
char delim[] = " ";
char *ptr = strtok(line, delim);
char **tokens = (char**) malloc(sizeof(char) * MAX);
int index =0;
while(ptr != NULL)
{
tokens[index]=ptr;
index++;
// printf("'%s'\n", ptr);
ptr = strtok(NULL, delim);
}
return tokens;
}
// write to file
void writeBye(char *filename){
FILE *fptr;
// opening file in writing mode
fptr = fopen(filename, "w");
// exiting program
if (fptr == NULL) {
printf("Error!");
exit(1);
}
fprintf(fptr, "%s", "Bye!\n");
fclose(fptr);
}
int main(int argc, char** argv)
{
if(argc < 2){
printf("Please insert exitfile as an argument!\n");
return;
}
while(1){
char *line;
char **tokens;
line = readcommand();
tokens = splitcommand(line);
if(strcmp(tokens[0],"exit")==0){
writeBye(argv[1]);
exit(0);
}
if(fork()==0){
if(execvp(tokens[0], tokens) == -1){
perror("The following error occured: ");
}
exit(1);
}else
wait(0);
}
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment