わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。

プロセスを起動する

プロセスの起動は、CreateProcess()関数で行います。CreateProcess()関数で起動した プロセスは起動元のプロセスと平行で動作しますので、CreateProcess()関数は起動した プロセスの終了は待ちません。プロセスの終了まで待機したい場合は、WaitForSingliOnject() 関数などで待機してください。

CreateProcess()関数から取得できるPROCESS_INFORMATIONの情報 にプロセスのハンドル情報が返ってきます。このハンドルの情報は、必要が無くなった時点で CloseHandle()関数で解放する必要があります。

#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <windows.h>



/*
	プロセスを起動する
*/
int _tmain
(
	  int argc
	, _TCHAR* argv[]
)
{
	// 標準出力にユニコード出力する
	setlocale( LC_ALL, "Japanese" );

	HRESULT hResult = E_FAIL;


	STARTUPINFO         tStartupInfo = { 0 };
	PROCESS_INFORMATION tProcessInfomation = { 0 };

	/*
		プロセスの起動(notepadを起動する)
	*/
	BOOL bResult = CreateProcess(
			  L"c:¥¥Windows¥¥System32¥¥notepad.exe"
			, L""
			, NULL
			, NULL
			, FALSE
			, 0
			, NULL
			, NULL
			, &tStartupInfo
			, &tProcessInfomation
		);
	if ( 0  == bResult ) {
		return( HRESULT_FROM_WIN32( ::GetLastError() ) );
	}


	/*
		プロセスの終了を待つ
	*/
	DWORD dwResult = ::WaitForSingleObject(
			  tProcessInfomation.hProcess
			, INFINITE
		);
	if ( WAIT_FAILED  == dwResult ) {
		hResult = HRESULT_FROM_WIN32( ::GetLastError() );
		goto err;
	}


	/*
		プロセスの終了コードを取得する
	*/
	DWORD dwExitCode;
	bResult = ::GetExitCodeProcess(
			  tProcessInfomation.hProcess
			, &dwExitCode
		);
	if ( 0 == bResult ) {
		hResult = HRESULT_FROM_WIN32( ::GetLastError() );
		goto err;
	}

	// 終了コードの表示
	wprintf( L"dwExitCode = %d¥n", dwExitCode );


err:
	// ハンドルの解放
	::CloseHandle( tProcessInfomation.hProcess );
	::CloseHandle( tProcessInfomation.hThread  );

	// 正常終了
	return( 0 );
}



実行結果

dwExitCode = 0






わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。