为什么cout会阻止后续代码在这里运行

Why does cout prevent subsequent code from running here?

本文关键字:代码 在这里 运行 cout 为什么      更新时间:2023-10-16

我正在开发一个基本的shell,但在下面的循环中,程序没有运行过标记的行(而是立即循环)。当我注释掉它时,整个块在再次循环之前完成。这是怎么回事?

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[]) {
  string input;
  const char *EOF="exit";
  string prompt=getenv("USER");
  prompt.append("@ash>");                                                                              
  while(true) {
    int parent=fork();
    if ( !parent ) {
      cout << prompt; //The program never gets past this point
      getline(cin,input);
      if (!input.compare(EOF))
        exit(0);
      cout << input << 'n';                                                                            
      execlp("ls", "-l", NULL);
      return 0;
    }
    else
      wait();
  }
}

添加这些#include s:

#include <sys/types.h>
#include <sys/wait.h>

则正确调用wait(2)

int status;
wait(&status);

您的代码wait()不会调用wait(2)系统调用。相反,它声明了一个类型为union wait的临时对象。如果您#include stdlib.h而不是sys/wait.h,那么您只能得到类型声明,而不能得到函数声明。

顺便说一句,如果您检查了wait调用的返回值:int result = wait(),您会收到一条信息性错误消息:

xsh.cc:26:错误:无法在初始化中将"wait"转换为"int"

相关文章: