Search code examples
c++linuxbashshellexecvp

Implementing bash operators for shell in c++


I'm trying to implement the ||, &&, and ; operators in a bash shell I am making. What I am trying to do, is use a int as a flag that would be set to 1 if it was successful or 0 if it was not. My issue is that even if I enter an invalid operation such as ls -apples it sets the flag to 1. I also get the error message

ls: invalid option -- 'e' Try 'ls --help' for more information

so I think that means it technically is executing? How do I keep track of whether execvp took a invalid operation? Here is my code:

    pid_t pid;
    pid_t waitId; 
    int status; 
    //forks into two processes 
    pid = fork();
    //There was an error during fork
    if (pid < 0) 
    {
        successFlag = 0; 
        perror("There was an error");
    } 
    else if (pid == 0) 
    {
        //must be cast because our function expects a char *const argv[]
        if (execvp(command[0], (char**)command) < 0) 
        { 
            //error at execvp
            successFlag = 0; 
            perror("There was an error executing the process");
        }
            exit(EXIT_FAILURE);
    }

    else 
    {
        do 
        {
          waitId = waitpid(pid, &status, WUNTRACED | WCONTINUED);
          if(waitId == -1){
              successFlag = 0; 
              perror("Error in parent process");
              exit(EXIT_FAILURE);
          }

        } 

        while (!WIFEXITED(status) && !WIFSIGNALED(status));
    }
    //use this flag to determine whether the process was a success
    successFlag = 1;

Solution

  • The solution was to look at the number that status returns. The sign would tell you whether it was successful or not.