|
|
1.1 root 1: /* Standard output handle/standard error handle redirection test
2: program */
3:
4: #include <stdio.h>
5: #include <io.h>
6: #include <string.h>
7: #include <windows.h>
8:
9: /* This function opens up a handle to CONOUT$ so that we can be
10: guaranteed to get error messages to the console even if the standard
11: handles are redirected. */
12:
13: void myError(HANDLE h, char *api, int line)
14: {
15: char buf[512];
16: BOOL fSuccess;
17: DWORD cBytesWritten;
18: HANDLE hConout;
19:
20: sprintf(buf, "%s: Error %d from %s on line %d\n", __FILE__, GetLastError(),
21: api, line);
22: fSuccess = WriteFile(h, buf, strlen(buf), &cBytesWritten, NULL);
23: if (!fSuccess)
24: {
25: hConout = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE,
26: FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
27: FILE_ATTRIBUTE_NORMAL, NULL);
28: sprintf(buf, "%s: Error %d from %s on line %d\n", __FILE__,
29: GetLastError(), api, line);
30: WriteFile(hConout, buf, strlen(buf), &cBytesWritten, NULL);
31: CloseHandle(hConout);
32: }
33: return;
34: }
35:
36: /* get the standard output handle and standard error handle and
37: write a message to each */
38:
39: int main()
40: {
41: DWORD cBytesWritten;
42: HANDLE hStdErr, hStdOut, hConout;
43: BOOL fSuccess;
44: char *stdErrMsg = "Hello from child to standard error!\n";
45: char *stdOutMsg = "Hello from child to standard output!\n";
46:
47: hConout = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE,
48: FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
49: FILE_ATTRIBUTE_NORMAL, NULL);
50: if ((int) hConout == -1)
51: Beep(5000,500); /* no reliable way of reporting errors to the console */
52: /* if we can't open a console handle */
53: hStdErr = GetStdHandle(STD_ERROR_HANDLE);
54: if ((int) hStdErr == -1)
55: myError(hConout, "GetStdHandle", __LINE__);
56: hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
57: if ((int) hStdOut == -1)
58: myError(hConout, "GetStdHandle", __LINE__);
59: fSuccess = WriteFile(hStdErr, stdErrMsg, strlen(stdErrMsg),
60: &cBytesWritten, NULL);
61: if (!fSuccess)
62: myError(hConout, "WriteFile", __LINE__);
63: fSuccess = WriteFile(hStdOut, stdOutMsg, strlen(stdOutMsg),
64: &cBytesWritten, NULL);
65: if (!fSuccess)
66: myError(hConout, "WriteFile", __LINE__);
67: CloseHandle(hConout);
68: return(0);
69: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.