Why does cout prevent subsequent code from running here?

拟墨画扇 提交于 2020-01-15 09:54:08

问题


I'm working on a rudimentary shell, but in the loop below, the program doesn't run past the marked line (it immediately loops instead). When I comment it out, the entire block completes before looping again. What's going on here?

#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:


Add these #includes:

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

then invoke wait(2) correctly:

int status;
wait(&status);

Your code, wait(), doesn't invoke the wait(2) system call. Rather, it declares a temporary object of type union wait. If you #include stdlib.h but not sys/wait.h, then you only get the type declaration, not the function declaration.

By the way, if you had checked the return value of the wait call: int result = wait(), you would have received an informative error message:

xsh.cc:26: error: cannot convert ‘wait’ to ‘int’ in initialization



来源:https://stackoverflow.com/questions/9279130/why-does-cout-prevent-subsequent-code-from-running-here

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!