user1209326
user1209326

Reputation: 825

Why does cout prevent subsequent code from running here?

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

Upvotes: 1

Views: 180

Answers (1)

Robᵩ
Robᵩ

Reputation: 168646

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

Upvotes: 6

Related Questions