C++ commands executing out of order
I am attempting to make a simple shell program, and looking at a few examples have seen that most people use getline() to get input, however I have been trying to use read() and noticed a weird bug that I was wondering if other people saw or knew the cause of.
When I run the code using getline, everything works fine. After running the program I get the terminal name to show up and it is ready to accept input. When I use read it seems to be executing the name of the shell after taking in input. This seems to occur no matter what I do. the line to display the shell name is
cout << "SweetShell-> ";
and then AFTER this line I either run the read command, or even call another process which then runs the read command, and either way printing "SweetShell-> " happens AFTER the input.
Even weirder during testing I had a block of code like:
cout << "SweetShell-> ";
int test = read(0,buf,MAX_ARGS);
//temp is a string that is set to the input
cout << temp << " " << test;
and the output looked something like this:
3SweetShell-> ls
meaning it printed the spaces, then test, then the first开发者_高级运维 cout, and finally temp. Anyone have any idea what is going on with this?
You should try "flushing" the output buffer to make sure it prints in order. Try:
cout << "SweetShell-> " << std::flush;
int test = read(0,buf,MAX_ARGS);
//temp is a string that is set to the input
cout << temp << " " << test << std::flush;
Because the output is buffered, you need to flush
the output before trying to read()
your input.
Incidentally, be careful when combining raw OS-level read(2)
and write(2)
operations with buffered IO operations; while you can certainly use them both in the same program, using them both on the same file or socket is going to create trouble; so sticking with one form or the other will reduce the likelihood of introducing flaws in the future.
The crucial thing is that std::cout
and std::cin
are tied (see http://www.cplusplus.com/reference/iostream/ios/tie/) - this means that streaming operations on std::cin
will first trigger a flush on std::cout
. But, you're using the libC read(...)
function which bypasses the C++ streams library altogether, therefore there's no chance for the flush to be invoked. You could use std::cin.read()
instead.
Why not use cin >> test
? I always use <iostream>
functions for console I/O; they work very well.
精彩评论