Why does cout prevent subsequent code from running?

I am working on a rudimentary shell, but in the loop below the program does not go past the highlighted line (it is immediately looped). When I comment on this, the whole block ends before the loop repeats. 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
source share
1 answer

Add these #include s:

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

then wait(2) correctly:

 int status; wait(&status); 

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

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

xsh.cc:26: error: cannot convert 'wait to' int to initialization

+6
source

Source: https://habr.com/ru/post/1390865/


All Articles