在c++中实现shell的bash操作符

Implementing bash operators for shell in c++

本文关键字:bash 操作符 shell 实现 c++      更新时间:2023-10-16

我正在尝试在我正在制作的bash shell中实现||, &&;操作符。我要做的是使用int作为标志,如果成功,则设置为1,如果失败,则设置为0。我的问题是,即使我输入一个无效的操作,如ls -apples,它将标志设置为1。我还得到错误消息

ls:无效选项——'e'尝试'ls——help'获取更多信息

所以我认为这意味着它在执行?我如何跟踪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返回的数字。这个标志会告诉你是否成功。