在 C++ 中为 shell 实现 bash 运算符

Implementing bash operators for shell in c++

我正在尝试在我正在制作的 bash shell 中实现 ||&&; 运算符。我想做的是使用 int 作为标志,如果成功则设置为 1,否则设置为 0。我的问题是,即使我输入了无效操作,例如 ls -apples,它也会将标志设置为 1。我也收到错误消息

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

所以我认为这意味着它在技术上正在执行? 如何跟踪 execvp 是否进行了无效操作? 这是我的代码:

    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;

解决方案是查看 status returns 的数字。这个标志会告诉你它是否成功。