FreeRDP
Loading...
Searching...
No Matches
TestFileGetStdHandle.c
1
22#include <winpr/file.h>
23#include <winpr/handle.h>
24#include <string.h>
25#include <stdio.h>
26
27static BOOL write_std_handle(DWORD nStdHandle, const char* name)
28{
29 const char buf[] = "happy happy\n";
30 DWORD bytesWritten = 0;
31
32 HANDLE h = GetStdHandle(nStdHandle);
33 if (h == INVALID_HANDLE_VALUE)
34 {
35 (void)fprintf(stderr, "GetStdHandle(%s) failed ;(\n", name);
36 return FALSE;
37 }
38 if (!WriteFile(h, buf, strnlen(buf, sizeof(buf)), &bytesWritten, nullptr))
39 {
40 (void)fprintf(stderr, "WriteFile(%s) failed\n", name);
41 return FALSE;
42 }
43 if (bytesWritten != strnlen(buf, sizeof(buf)))
44 {
45 (void)fprintf(stderr, "write to %s failed\n", name);
46 return FALSE;
47 }
48 return TRUE;
49}
50
51int TestFileGetStdHandle(int argc, char* argv[])
52{
53 WINPR_UNUSED(argc);
54 WINPR_UNUSED(argv);
55
56 /* STD_INPUT_HANDLE is requested first on purpose: every standard stream needs its own
57 * handle, regardless of which one a process asks for first. */
58 const HANDLE si = GetStdHandle(STD_INPUT_HANDLE);
59 const HANDLE so = GetStdHandle(STD_OUTPUT_HANDLE);
60 const HANDLE se = GetStdHandle(STD_ERROR_HANDLE);
61 if ((si == INVALID_HANDLE_VALUE) || (so == INVALID_HANDLE_VALUE) ||
62 (se == INVALID_HANDLE_VALUE))
63 {
64 (void)fprintf(stderr, "GetStdHandle failed ;(\n");
65 return -1;
66 }
67 if ((si == so) || (si == se) || (so == se))
68 {
69 (void)fprintf(stderr, "GetStdHandle returned one handle for different streams\n");
70 return -1;
71 }
72 if ((GetStdHandle(STD_INPUT_HANDLE) != si) || (GetStdHandle(STD_OUTPUT_HANDLE) != so) ||
73 (GetStdHandle(STD_ERROR_HANDLE) != se))
74 {
75 (void)fprintf(stderr, "GetStdHandle returned a new handle on a repeated call\n");
76 return -1;
77 }
78
79 if (!write_std_handle(STD_OUTPUT_HANDLE, "STD_OUTPUT_HANDLE") ||
80 !write_std_handle(STD_ERROR_HANDLE, "STD_ERROR_HANDLE"))
81 return -1;
82
83 /* the standard handles are process wide, closing them must not invalidate them */
84 (void)CloseHandle(si);
85 (void)CloseHandle(so);
86 (void)CloseHandle(se);
87 if (!write_std_handle(STD_OUTPUT_HANDLE, "STD_OUTPUT_HANDLE") ||
88 !write_std_handle(STD_ERROR_HANDLE, "STD_ERROR_HANDLE"))
89 return -1;
90
91 return 0;
92}