Shell 编写 HereDoc 脚本:在完成从 HERE 文档的读取后停止进程从标准输入读取“”
Shell Script HereDoc : Stopping a process from reading "" from stdin after it has finished reading from HERE doc
我有一个程序,逻辑如下,不断读取输入并打印出读取的输入。
int main()
{
while(1){
std::string str;
std::cin>>str; // Read a string
std::cout<<"\""<<str<<"\""<<std::endl<<std::flush;
str.clear();
sleep(1);
}
}
现在我从 ksh 启动这个程序,使用 HERE 文档提供几行输入。
abi@linux:~/Tst> ./a.out << EOF
> Hi
> How
> are
> You
> EOF
"Hi"
"How"
"are"
"You"
""
""
""
""
""
""
*i entered <ctrl+C> here to stop the program*
abi@linux:~/Tst>
我的问题是,我只提供了 4 行作为来自 HERE 文档的输入,
但输入完后,a.out不断读取NULL作为输入,打印出""。
为什么会这样?
您提供的程序将永远不会终止;因为你有一个
while(1) {
do_things_forever();
}
因为它永远不会终止,一旦您到达输入的末尾,stdin 将为 null,所以它完全按照您的要求执行。
您可能想要类似于:
std::string str;
while( !( std::cin >> str ).eof() ) {
std::cout << '"' << str << '"' << std::endl << std::flush;
str.clear();
sleep(1);
}
我有一个程序,逻辑如下,不断读取输入并打印出读取的输入。
int main()
{
while(1){
std::string str;
std::cin>>str; // Read a string
std::cout<<"\""<<str<<"\""<<std::endl<<std::flush;
str.clear();
sleep(1);
}
}
现在我从 ksh 启动这个程序,使用 HERE 文档提供几行输入。
abi@linux:~/Tst> ./a.out << EOF
> Hi
> How
> are
> You
> EOF
"Hi"
"How"
"are"
"You"
""
""
""
""
""
""
*i entered <ctrl+C> here to stop the program*
abi@linux:~/Tst>
我的问题是,我只提供了 4 行作为来自 HERE 文档的输入,
但输入完后,a.out不断读取NULL作为输入,打印出""。
为什么会这样?
您提供的程序将永远不会终止;因为你有一个
while(1) {
do_things_forever();
}
因为它永远不会终止,一旦您到达输入的末尾,stdin 将为 null,所以它完全按照您的要求执行。
您可能想要类似于:
std::string str;
while( !( std::cin >> str ).eof() ) {
std::cout << '"' << str << '"' << std::endl << std::flush;
str.clear();
sleep(1);
}