pcre2grep: avoid portability minefield with buffered fseek(stdin) (#36)

To allow pcre2grep to do an early exit in a resumable way, -m uses
fseek on stdin, which is sadly not supported in several platforms.

Most of the conflicting issues come from the fact that managing the
position while buffering is not trivial, and is therefore an optional
feature[1] of POSIX.1-2017

Workaround this by removing the buffer to stdin, if the -m option is
being used.  There is likely not a significant performance benefit
even for the platforms that support it, but it could be conditionally
added in that case, later.

Fixes: #10

[1] https://pubs.opengroup.org/onlinepubs/9699919799/functions/fseek.html
This commit is contained in:
Carlo Marcelo Arenas Belón 2021-11-09 09:15:38 -08:00 committed by GitHub
parent 1ed34b9cb1
commit dae475092d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 6 additions and 0 deletions

View File

@ -3275,6 +3275,7 @@ FILE *zos_test_file;
if (strcmp(pathname, "-") == 0)
{
if (count_limit >= 0) setbuf(stdin, NULL);
return pcre2grep(stdin, FR_PLAIN, stdin_name,
(filenames > FN_DEFAULT || (filenames == FN_DEFAULT && !only_one_at_top))?
stdin_name : NULL);
@ -4482,6 +4483,11 @@ no file arguments, search stdin, and then exit. */
if (file_lists == NULL && i >= argc)
{
/* Using a buffered stdin, that then is seek is not portable,
so attempt to remove the buffer, to workaround reported issues
affecting several BSD and AIX */
if (count_limit >= 0)
setbuf(stdin, NULL);
rc = pcre2grep(stdin, FR_PLAIN, stdin_name,
(filenames > FN_DEFAULT)? stdin_name : NULL);
goto EXIT;