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

时间:2012-02-14 14:59:55

标签: 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();
  }
}

1 个答案:

答案 0 :(得分:6)

添加这些#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'