#include <unistd.h>
int main(int argc, char* argv[])
{
char buf[500];
read(0, buf, 5);
return 0;
}
The above read 5 characters from stdin,but if I input more than 5:
12345morethan5
[root@ test]# morethan5
-bash: morethan5: command not found
The remaining characters will be executed as shell commands.
Is this kind of behavior defined by standard?
Sort of 🙂
Your program reads 5 characters, and that’s it. Not less, not more. The rest remain in the terminal buffer and get sent to your shell once your C program terminates.
Since you are using
read(), which is a raw system call, instead of any of the C stdio buffering alternatives this behaviour is not just expected, but required.From the POSIX standard on
read():I.e.
read()should never read more bytes from the file descriptor than requested.From the related part on terminals:
Note: normally your shell will still have an open file descriptor for the terminal, until you end the session.