Executing C ++ Commands

I'm trying to make a simple shell program, and looking at a few examples, most people use getline () to enter input, however I try to use read () and noticed a strange error that other people saw or knew the reason.

When I run the code using getline, everything works fine. After starting the program, I get the name of the terminal that will be displayed, and it is ready to accept input. When I use reading, it seems to execute the shell name after entering the input. This seems to be happening no matter what I do. string to display shell name

cout << "SweetShell-> "; 

and then AFTER this line, I either start the read command, or even call another process, which then starts the read command, and in any case, printing "SweetShell->" occurs AFTER input.

Even 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 result looked something like this:

  3SweetShell-> ls 

means he printed spaces, then tested, then first cout and finally temp. Does anyone know what is happening with this?

+6
c ++ order order-of-operations
source share
4 answers

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; 
+11
source share

Since the output is buffered, you need to flush output before trying to read() your input.

By the way, be careful when combining raw read(2) and write(2) operations at the OS level with buffered I / O; while you can use them in the same program, using them in the same file as in the socket will create problems; so sticking one or another form will reduce the likelihood of introducing defects in the future.

+4
source share

Most importantly, std::cout and std::cin bound (see http://www.cplusplus.com/reference/iostream/ios/tie/ ) - this means that streaming operations on std::cin will first call reset to std::cout . But you use the libC read(...) function, which generally bypasses the C ++ thread library, so there is no way to run a flash. You can use std::cin.read() .

+4
source share

Why not use cin >> test ? I always use the <iostream> functions to input / output the console; they work very well.

0
source share

All Articles