Standard Handles and win32

Like *nix, a Windows process has three standard devices for input, output, and error reporting; to access these standard devices, Windows needs a HANDLE that is acquired with the GetStdHandle() function. The GetStdHandle() function accepts a DWORD argument and returns a HANDLE on success and INVALID_HANDLE_VALUE otherwise.

The parameter can be one of three values, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, and STD_ERROR_HANDLE.

#include <Windows.h>
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
	printf("%x \n", STD_INPUT_HANDLE);
	printf("%x \n", STD_OUTPUT_HANDLE);
	printf("%x \n", STD_ERROR_HANDLE);

	return 0;
}

The GetStdHandle() function does not create a new or duplicate handle on a standard device. No matter how many times we call GetStdHandle(), the function returns the same handle.

#include 
#include 

int _tmain(int argc, _TCHAR* argv[])
{
	char *szString = "For great justice! ";
	DWORD dwBytesWritten;
	HANDLE hStdin = GetStdHandle(STD_OUTPUT_HANDLE);

	if(hStdin == INVALID_HANDLE_VALUE){
		printf("Error accessing standard input.\n");
	}

	if(WriteFile(hStdin, szString, strlen(szString), &dwBytesWritten, NULL)){
		printf("No problems writing to standard input.\n");
	}

	return 0;
}

The SetStdHandle() function enables us to redirect standard input, standard output, and standard error. The SetStdHandle() function takes two arguments; the first argument is a DWORD value indicating whether we are redirecting standard input, standard output, or standard error, and the second value is a handle to the file we want to redirect to.

#include <Windows.h>
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{

	HANDLE hFile;

	hFile = CreateFile("textfile.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

	if(hFile == INVALID_HANDLE_VALUE){
		printf("Error opening file.");
		return -1;
	}

	if(SetStdHandle(STD_OUTPUT_HANDLE, hFile)==FALSE){
		printf("Error setting standard handle.\n");
		return -2;
	}

	//will print to the file
	//not to the console
	printf("I survived the Kobayashi Maru!\n");
	printf("Photons be free!\n");
	
	return 0;
}

Note that if you call GetStdHandle() after redirecting the standard input, output or error you will get the redirected handle! To recover standard output to the console screen, call CreateFile() with CONOUT$, likewise, a call to CreateFile() with CONIN$ will recover a handle to standard input.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s