程序卡在wait()上

program stuck on wait()

本文关键字:wait 程序      更新时间:2023-10-16

我遇到了一个进程处于等待状态的问题。我一直在排除这个问题,这是我的shell程序目前唯一的错误。

问题是当用户输入"退出"时程序应该退出。然而,如果用户输入了一个无效的字符串,程序就会陷入wait()。这导致必须键入exit两次才能退出,而不是一次。如何阻止这种情况发生,当用户输入一个哑字符串时,如何退出wait()调用?

复制步骤:

  • 使用gcc/g++编译和运行
  • 键入你选择的脏话
  • 类型出口
  • 注意,程序没有退出(因为它停留在wait()上,但提示
  • 再次键入exit
  • 程序退出


#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;
};

它可能必须使用以下行:

exitstatus==true;

你的意思是:

existatus = true;

gcc无论如何都会为它报告类似的内容(-Wall):

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

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

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

只需在您的execvp()呼叫后添加一个exit(EXIT_FAILURE);即可。