首页 > 解决方案 > Exit(0) 不结束程序

问题描述

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

标签: c++shellforkexit-code

解决方案


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


推荐阅读