退出(0)未结束程序

时间:2018-12-20 17:32:28

标签: c++ shell fork exit-code

我正在制作一个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。

1 个答案:

答案 0 :(得分:2)

您的父进程陷入了while(1)循环中。在break;之后添加wait(NULL);行。