程序卡在wait()上
program stuck on wait()
我遇到了一个进程处于等待状态的问题。我一直在排除这个问题,这是我的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);
即可。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- std::condition_variable::wait()如何评估给定的谓词
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 在 UWP 应用程序中,future.wait() 在尝试同步来自异步方法的响应时继续等待
- 程序卡在wait()上
- 当应用程序在没有适当的 wait() 调用的情况下关闭时,QThread 会发生什么