【发布时间】:2018-12-20 17:32:27
【问题描述】:
我正在制作一个 shell 并试图理解 fork 它的功能(只有有问题的代码如下所示)。
但是,在添加 fork(); 之后,我的 shell 并没有通过 exit 命令退出。我知道我可以使用kill(pid, SIGKILL) 来实现这一点,但我不想显示任何退出状态。我认为exit(0); 应该可以在不需要kill(pid, SIGKILL) 的情况下工作。
简单的代码解释会有很大帮助。
更新:我想接受连续命令直到退出。
#include <iostream>
#include <sys/wait.h>
#include <vector>
#include <string>
#include <chrono>
#include <algorithm>
#include <unistd.h>
using namespace std;
typedef struct cmds{
string cmd;
} cmds;
bool operator<(cmds &as1, cmds &bs1){
return as1.durr<bs1.durr;
}
int main() {
vector <cmds> lst;
cmds ant;
string cmd;
pid_t pid = fork() ;
while (1){
if(pid==0){
cout<<"$>";
getline(cin,cmd);
ant.cmd=cmd;
string comd;
for(int i=0;i<cmd.length();i++){
if(cmd[i]!=' ')
comd+=cmd[i];
}
if(comd=="exit"){
exit(0);
}
else{
char s[256]="";
for (int i=0; i<cmd.length(); i++)
s[i]=cmd[i];
}
lst.push_back(ant);
}
else
wait(NULL);
}
}
**Expected output** - //The shell should end without any cout or exit status//
**Actual output** - //The shell does not end and you can type anything and enter and continue - however no '$' is present and you cannot use any shell commands//
对任何乱七八糟的写作表示歉意 - 用于写问题的新 UI 很难使用。
【问题讨论】:
-
我被否决的任何特殊原因以及如何确保永远不会发生?
-
您应该尝试通过调试器运行您的程序。
-
我尝试了调试器,但仍然无法解决问题。 :(
-
调试器说你的程序处于什么状态?
-
我说的是在你中断程序处于错误状态后检查堆栈的状态