Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/wait.h>
- #define ARGLIMIT 64
- #define ARGLENGH 256
- #define TRUE 1
- #define FALSE 0
- #define ETMARGS \
- {printf("Fatal error: only 8 arguments are allowed\n"); return 1;}
- static int cmd_counter, st;
- char *argv[ARGLIMIT];
- void init(){
- cmd_counter=0;
- printf("Welcome in Dummyshell!\n");
- fflush(stdout);
- }
- void leave_shell(void){
- int i;
- if(errno == 0) for(i=0;i<ARGLIMIT-1;i++) free(argv[i]);
- printf("You're leaving Dummyshell...\n");
- fflush(stdout);
- }
- void type_prompt(){
- printf("[cmd # %d][stat: %d] @ Dush £: ",cmd_counter,st);
- fflush(stdout);
- cmd_counter++;
- }
- int read_cmd_line(char *argv[]){
- char *arg_buffer = (char*) malloc(sizeof(char)*ARGLENGH), *it;
- int i=0, l1=0, l2=0;
- fgets(arg_buffer,ARGLENGH,stdin);
- fflush(stdin);
- for(it=arg_buffer; it != '\0'; it++){
- if(i >= ARGLIMIT -1) ETMARGS
- argv[i] = (char*) malloc(sizeof(char)*ARGLENGH);
- l1 = strlen(it);
- strncpy(argv[i],it,l1);
- argv[i][l1-1] = '\0';
- it = strchr(it,' ');
- if (it == NULL) break;
- l2 = strlen(it);
- argv[i][l1-l2] = '\0';
- i++;
- }
- argv[i+1] = NULL;
- return 0;
- }
- int cmd_exit(char *argv[]){
- if(strcmp(argv[0],"exit")==0) return 1;
- return 0;
- }
- static void execute(int *st, char *argv[]){
- pid_t pid;
- switch(pid=fork()){
- case -1 :{
- perror("Couldn't fork!\n");
- break;
- }
- case 0 :{
- execvp(argv[0],argv);
- perror("Couldn't execute!\n");
- break;
- }
- default :{
- if(waitpid(pid,st,0)==-1){
- perror("Waitpid: ");
- exit(errno);
- }
- }
- }
- }
- int main(){
- if(atexit(leave_shell)) perror("Atexit failed! Possible memory leak\n");
- init();
- while(TRUE){
- type_prompt();
- if(read_cmd_line(argv)!=-1){
- if(cmd_exit(argv)) exit(EXIT_SUCCESS);
- execute(&st,argv);
- }
- else fprintf(stderr,"Invalid command!\n");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement