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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With