10

I have to develop a simple shell in C using system calls fork()/execvp(). So far my code takes in a command, splits it up using strtok into an array argv and then I call fork to create a child and execute the command. Im working on this in ubuntu where most of the commands are in the /bin/ directory, so I append the program name (for example /bin/ls) and use that for the first arg of execvp and then I give it the argv array. My program works if I type in the command "ls", but when trying other commands or even "ls -l" I'm getting an "ls: invalid option." Im not sure what I'm doing wrong here.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_LEN 1024

int main(){
    char line[BUFFER_LEN];  //get command line
    char* argv[100];        //user command
    char* path= "/bin/";    //set path at bin
    char progpath[20];      //full file path
    int argc;               //arg count

while(1){

    printf("My shell>> ");                    //print shell prompt

        if(!fgets(line, BUFFER_LEN, stdin)){  //get command and put it in line
        break;                                //if user hits CTRL+D break
    }
    if(strcmp(line, "exit\n")==0){            //check if command is exit
        break;
    }

    char *token;                  //split command into separate strings
    token = strtok(line," ");
    int i=0;
    while(token!=NULL){
        argv[i]=token;      
        token = strtok(NULL," ");
        i++;
    }
    argv[i]=NULL;                     //set last value to NULL for execvp

    argc=i;                           //get arg count
    for(i=0; i<argc; i++){
        printf("%s\n", argv[i]);      //print command/args
    }
    strcpy(progpath, path);           //copy /bin/ to file path
    strcat(progpath, argv[0]);            //add program to path

    for(i=0; i<strlen(progpath); i++){    //delete newline
        if(progpath[i]=='\n'){      
            progpath[i]='\0';
        }
    }
    int pid= fork();              //fork child

    if(pid==0){               //Child
        execvp(progpath,argv);
        fprintf(stderr, "Child process could not do execvp\n");

    }else{                    //Parent
        wait(NULL);
        printf("Child exited\n");
    }

}
} 
C1116
  • 173
  • 2
  • 5
  • 16
  • You don't need to append `/bin` to the filename unless your PATH environment variable does not contain `/bin`. Also, this is unsafe, it's probably not related to the problem, but unsafe `while(token!=NULL)` make it `while(token!=NULL && i < 100)` – Iharob Al Asimi Feb 13 '15 at 14:59

2 Answers2

7

The invalid option is because fgets() keeps the '\n' when you press enter, try this

if(!fgets(line, BUFFER_LEN, stdin))
    break;
size_t length = strlen(line);
if (line[length - 1] == '\n')
    line[length - 1] = '\0';

when you are trying to call ls -l you are passing "-l\n" as the option, hence the message.

You will have to change

strcmp(line, "exit\n")

to

strcmp(line, "exit")
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • A good place to see working simple shell in C [C-Shell](http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/exec.html) – EsmaeelE Mar 03 '18 at 19:07
  • They use harmful `gets()` for save standard input [see why](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used), i try to replace it with `fgets()`, [see other methods](https://stackoverflow.com/questions/3302255/c-scanf-vs-gets-vs-fgets), but in case of `ls` command i have same error. `ls: cannot access '': No such file or directory ` – EsmaeelE Mar 03 '18 at 19:19
  • some other links: 1. [tutorial](https://brennan.io/2015/01/16/write-a-shell-in-c/) 2. [SO](https://stackoverflow.com/questions/27541910/how-to-use-execvp) 3. [SE](https://codereview.stackexchange.com/questions/67746/simple-shell-in-c) – EsmaeelE Mar 03 '18 at 19:25
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

#define BUFFER_LEN 1024

int main(){
    char user_input[BUFFER_LEN];  //get command line
    char* argv[120]; //user command
    int argc ; //argument count
    char* path= "/bin/";  //set path at bin  
    char file_path[50];//full file path

    while(1){
        
        printf("Simple Shell>> ");  // Greeting shell during startup               
        
        if(!fgets(user_input,BUFFER_LEN, stdin)){
            break;  //break if the command length exceed the defined BUFFER_LEN
        }
        
        size_t length = strlen(user_input);

        if(length == 0){
            break;
        }

        if (user_input[length - 1] == '\n'){
            user_input[length - 1] = '\0'; // replace last char by '\0' if it is new line char
        }
        
        //split command using spaces
        char *token;                  
        token = strtok(user_input," ");
        int argc=0;
        if(token == NULL){
            continue;
        }
        while(token!=NULL){
            argv[argc]=token;      
            token = strtok(NULL," ");
            argc++;
        }
        
        argv[argc]=NULL; 
        
        strcpy(file_path, path);  //Assign path to file_path 
        strcat(file_path, argv[0]); //conctanate command and file path           

        if (access(file_path,F_OK)==0){  //check the command is available in /bin
        
            pid_t pid, wpid;
            int status;
            
            pid = fork();
            if (pid == 0) { //child process 
                if (execvp(file_path,argv) == -1) {
                  perror("Child proccess end"); 
                }
                exit(EXIT_FAILURE);
            } 
            else if (pid > 0) { // parent process
                wpid = waitpid(pid, &status, WUNTRACED); 
                while (!WIFEXITED(status) && !WIFSIGNALED(status)){
                    wpid = waitpid(pid, &status, WUNTRACED); 
                }
            } 
            else {
                perror("Fork Failed"); //process id can not be null 
            }
        }
        else {
            printf("Command is not available in the bin\n"); //Command is not available in the bin
        }

    }
}