Skip to content

Commit 5589467

Browse files
committed
Improved error checking of standard I/O streams.
1 parent 4f942a3 commit 5589467

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

tee.c

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ static const wchar_t *get_filename(const wchar_t *filePath)
9090
static BOOL is_null_device(const wchar_t *filePath)
9191
{
9292
filePath = get_filename(filePath);
93-
if ((to_lower(filePath[0U]) == L'n') && (to_lower(filePath[1U]) == L'u') || (to_lower(filePath[2U]) == L'l'))
93+
if ((to_lower(filePath[0U]) == L'n') && (to_lower(filePath[1U]) == L'u') && (to_lower(filePath[2U]) == L'l'))
9494
{
9595
return ((filePath[3U] == L'\0') || (filePath[3U] == L'.'));
9696
}
@@ -398,7 +398,10 @@ int wmain(const int argc, const wchar_t *const argv[])
398398
const HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE), hStdOut = GetStdHandle(STD_OUTPUT_HANDLE), hStdErr = GetStdHandle(STD_ERROR_HANDLE);
399399
if (!(VALID_HANDLE(hStdIn) && VALID_HANDLE(hStdOut) && VALID_HANDLE(hStdErr)))
400400
{
401-
OutputDebugStringA("[tee-win32] System error: Failed to initialize standard handles!\n");
401+
if (VALID_HANDLE(hStdErr))
402+
{
403+
write_text(hStdErr, L"[tee] System error: Failed to initialize standard I/O handles!\n");
404+
}
402405
return -1;
403406
}
404407

@@ -459,6 +462,27 @@ int wmain(const int argc, const wchar_t *const argv[])
459462
return 1;
460463
}
461464

465+
/* Determine input type */
466+
const DWORD inputType = GetFileType(hStdIn);
467+
if (inputType == FILE_TYPE_UNKNOWN)
468+
{
469+
if (GetLastError() != NO_ERROR)
470+
{
471+
write_text(hStdErr, L"[tee] System error: Failed to initialize standard input stream!\n");
472+
return -1;
473+
}
474+
}
475+
476+
/* Validate output stream */
477+
if (GetFileType(hStdOut) == FILE_TYPE_UNKNOWN)
478+
{
479+
if (GetLastError() != NO_ERROR)
480+
{
481+
write_text(hStdErr, L"[tee] System error: Failed to initialize standard output stream!\n");
482+
return -1;
483+
}
484+
}
485+
462486
/* Open output file(s) */
463487
while ((argOff < argc) && (fileCount < ARRAYSIZE(hMyFiles)))
464488
{
@@ -505,9 +529,6 @@ int wmain(const int argc, const wchar_t *const argv[])
505529
}
506530
}
507531

508-
/* Are we reading from a pipe? */
509-
const BOOL isPipeInput = (GetFileType(hStdIn) == FILE_TYPE_PIPE);
510-
511532
/* Initialize the index */
512533
BYTE myFlag = 1U;
513534

@@ -543,7 +564,7 @@ int wmain(const int argc, const wchar_t *const argv[])
543564
if (!g_bytesTotal[myIndex])
544565
{
545566
ReleaseSRWLockExclusive(&g_rwLocks[myIndex]);
546-
if (isPipeInput)
567+
if (inputType == FILE_TYPE_PIPE)
547568
{
548569
continue; /*pipes may return zero bytes, even when more data can become available later!*/
549570
}

0 commit comments

Comments
 (0)