I have been struggling with a pretty simple issue writing a little program in C.
Getting input (commands, arguments, flags to be executed) via fgets()
works fine as long as the size of the input does not exceed 1024 bytes. After 1024 characters are typed, no more characters are accepted -- the prompt just stops. I assume reason for the problem doesn't lay in the fgets()
parameters/configuration because otherwise it would at least take the input up to defined size instead of blocking.
How can I make fgets()
accept lines as long as _SC_LINE_MAX
(2048
) bytes/chars?
Terminal drivers limit the length of input lines
As I noted in the comments, the trouble is almost certainly that your terminal driver won't allow you to enter lines that are longer than 1024 bytes; it won't allocate more storage. That applies in 'canonical' mode; see Canonical vs non-canonical terminal input for more information about that.
There's a simple test program (now in the question). When I run it on Mac OS X 10.11.4, I can enter 1023 characters plus newline, or 1024 characters but no newline until I delete one.
For the record, the input string was:
If you copy and paste that with the newline, it will probably be entered OK. If you add any more characters, you will probably get the terminal beeping at you.
There's another question (
fgets()
is limited to 1024 bytes — what can I use instead?) that almost certainly ran into the same problem — and really wasn't given much in the way of useful help.If you use a library such as the GNU
readline
library, it can put the terminal into non-canonical mode and then can handle longer lines because the terminal driver doesn't wait until the newline is entered before sending the data to the program. Rebuilding the kernel with a bigger limit on the terminal input line length is nominally an option on Linux-like systems, but not a task for the casual programmer.Meaning of
LINE_MAX
and related macrosAlso note that
_SC_LINE_MAX
is thesysconf()
code for determiningLINE_MAX
, which must be at least the value of{POSIX2_LINE_MAX}
(minimum 2048), which is documented as being:Note that a terminal is not a text file. This limit says that utilities such as
grep
must not mishandle lines that are 2048 bytes long, but it might get confused by longer lines (for example, because it reads 2048-byte chunks of a line, and does 'beginning of line' matches at the start of the second or subsequent chunks of a long line).The rationale for POSIX notes:
And the
{MAX_CANON}
referenced is described as:And elsewhere (
<limits.h>
), the minimum acceptable value for_POSIX_MAX_CANON
is 255.