【问题标题】:Exit(0) not ending the programmeExit(0) 不结束程序
【发布时间】: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 很难使用。

【问题讨论】:

  • 我被否决的任何特殊原因以及如何确保永远不会发生?
  • 您应该尝试通过调试器运行您的程序。
  • 我尝试了调试器,但仍然无法解决问题。 :(
  • 调试器说你的程序处于什么状态?
  • 我说的是在你中断程序处于错误状态后检查堆栈的状态

标签: c++ shell fork exit-code


【解决方案1】:

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

【讨论】:

  • 我想接受连续命令直到退出。休息;将在一个命令后停止它。
  • @UtsoRoy 只有你的子进程应该在while(1)循环中。
  • 如何在while(1)循环中只制作子进程?
  • 如何在while(1)循环中只做子进程? int pid = fork(); if (pid == -1) { /* fork failed */ exit(-1); } else if (pid == 0) { /* child */ while (1) { /* ... */ } } else { /* parent */ wait(pid); }
  • @UtsoRoy 您是否尝试按照答案提示插入带有break; 的行?
猜你喜欢
  • 1970-01-01
  • 2012-01-19
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多