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

use*_*326 1 c++ string cout

我正在研究一个基本的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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 6

添加这些#include:

#include <sys/types.h>
#include <sys/wait.h>
Run Code Online (Sandbox Code Playgroud)

然后wait(2)正确调用:

int status;
wait(&status);
Run Code Online (Sandbox Code Playgroud)

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

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

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