程序卡在等待()

时间:2015-02-25 07:24:25

标签: c++ debugging unix fork wait

我遇到了一个等待进程的问题。我一直在解决这个问题,这是我目前为我的shell程序唯一的错误。

问题是当用户进入“退出”时程序应该退出。但是,如果用户输入无效字符串,则程序似乎停留在wait()上。这导致必须键入exit两次退出而不是一次。如何阻止这种情况发生,如何在用户输入哑字符串时退出wait()调用?

重现的步骤:

  • 使用gcc / g ++编译并运行
  • 输入您选择的咒语
  • 键入exit
  • 注意程序没有退出(因为它停留在wait()但是提示
  • 再次输入
  • 程序退出


#include <iostream>
#include <unistd.h>
#include "stdlib.h"
#include "stdio.h"
#include <iostream>
#include <string>
#include <sys/wait.h>
#include <sstream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>

using std::string;

using std::cout;
using std::endl;


bool exitstatus;
int argsIndex = 0;
pid_t pid;
int main(void)
{  

    char * args[100];
    string check = "";           

    while(exitstatus==false)
    {
        cout<<"tinyshell:~>";
        std::getline(std::cin, check);
        if(check == "exit"){
            exitstatus==true;

        }

        if(exitstatus==false&&check!="cd..")
        {
            pid = fork();
            perror("");
            if (pid < 0) { /* error occurred */
                fprintf(stderr, "Fork Failed");
                //return 1;
            }
            else if (pid == 0 ) { /* child process */
                execvp(args[0],args);
                perror("");
            }
            else if(check!= "&"){/* parent will wait for the child to complete */
                wait(NULL);
                perror("");
                //  cout <<"Child Complete" << endl;
            }
            else
            {
            }
        }
    }
    return 0;
};

1 个答案:

答案 0 :(得分:0)

可能需要对此行做一些事情:

exitstatus==true;

你有没有意思:

existatus = true;
无论如何,

gcc会为此报告此类内容(-Wall):

warning: statement has no effect [-Wunused-value]
         exitstatus==true;

这是一个很好的例子,说明为什么启用警告是一种很好的做法......

您的代码还存在一个更微妙的问题。您没有检查execvp功能的结果。所以基本上如果你在shell中输入一些垃圾命令你的exec会失败,但你的子进程将继续运行与父进程相同的代码(循环)。

只需在exit(EXIT_FAILURE);来电后添​​加execvp()