问题描述
我在一个基本的shell,但在下面的循环,程序不会运行超过标记行(它立即循环改为)。当我注释掉它,整个块完成后再循环。这是怎么回事?
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();
}
}
推荐答案
这些 #include
s:
#include <sys/types.h>
#include <sys/wait.h>
然后调用:
int status;
wait(&status);
您的代码, wait()
调用 wait(2)
系统调用。相反,它声明一个类型为 union wait
的临时对象。如果 #include
stdlib.h
,但不是 sys / wait.h
,那么你只得到类型声明,而不是函数声明。
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.
顺便说一下,如果你检查了 wait
call: int result = wait()
,您会收到一条信息性的错误消息:
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:
这篇关于为什么cout会阻止后续代码在这里运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!