C++ で ::CreateProcess を呼び出して Windows 実行可能ファイルを起動するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/42531

  •  09-06-2019
  •  | 
  •  

質問

次のような例を探しています。

  1. EXEを起動します
  2. EXE が終了するのを待ちます。
  3. 実行可能ファイルが終了すると、すべてのハンドルが適切に閉じられます。
役に立ちましたか?

解決

このようなもの:

STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
    WaitForSingleObject(processInfo.hProcess, INFINITE);
    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);
}

他のヒント

に例があります http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx

を交換するだけです argv[1] プログラムを含む定数または変数で置き換えます。

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

void _tmain( int argc, TCHAR *argv[] )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    if( argc != 2 )
    {
        printf("Usage: %s [cmdline]\n", argv[0]);
        return;
    }

    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        argv[1],        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    ) 
    {
        printf( "CreateProcess failed (%d).\n", GetLastError() );
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}

アプリケーションが Windows GUI アプリケーションの場合、アプリケーションのメッセージが処理されないため、以下のコードを使用して待機することは理想的ではありません。ユーザーにとっては、アプリケーションがハングしたように見えます。

WaitForSingleObject(&processInfo.hProcess, INFINITE)

のようなもの 未テスト 以下のコードは、Windows メッセージ キューの処理を継続し、アプリケーションの応答性を維持できるため、より良い可能性があります。

//-- wait for the process to finish
while (true)
{
  //-- see if the task has terminated
  DWORD dwExitCode = WaitForSingleObject(ProcessInfo.hProcess, 0);

  if (   (dwExitCode == WAIT_FAILED   )
      || (dwExitCode == WAIT_OBJECT_0 )
      || (dwExitCode == WAIT_ABANDONED) )
  {
    DWORD dwExitCode;

    //-- get the process exit code
    GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);

    //-- the task has ended so close the handle
    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);

    //-- save the exit code
    lExitCode = dwExitCode;

    return;
  }
  else
  {
    //-- see if there are any message that need to be processed
    while (PeekMessage(&message.msg, 0, 0, 0, PM_NOREMOVE))
    {
      if (message.msg.message == WM_QUIT)
      {
        return;
      }

      //-- process the message queue
      if (GetMessage(&message.msg, 0, 0, 0))
      {
        //-- process the message
        TranslateMessage(&pMessage->msg);
        DispatchMessage(&pMessage->msg);
      }
    }
  }
}

実行ファイルがたまたまコンソール アプリの場合は、stdout と stderr を読み取ることに興味があるかもしれません。そのために、謙虚にこの例を参照してください。

http://support.microsoft.com/default.aspx?scid=kb;EN-US;q190351

これは少し長いコードですが、生成と読み取りにこのコードのバリエーションを使用しました。

準関連するメモですが、現在のプロセスよりも多くの権限を持つプロセスを開始したい場合 (たとえば、管理者権限を必要とする管理アプリを、通常のユーザーとして実行しているメイン アプリから起動する場合)、 Vista では、UAC ダイアログがトリガーされないため、CreateProcess() を使用してください (有効になっていると仮定します)。ただし、ShellExecute() を使用すると、UAC ダイアログがトリガーされます。

おそらくこれが最も完成度が高いでしょうか?http://goffconcepts.com/techarticles/development/cpp/createprocess.html

を使用することに留意してください WaitForSingleObject このシナリオでは問題が発生する可能性があります。以下は私のウェブサイトのヒントから抜粋したものです。

この問題は、アプリケーションにウィンドウはあるものの、メッセージを送出していないために発生します。生成されたアプリケーションがブロードキャスト ターゲットの 1 つで SendMessage を呼び出した場合 (HWND_BROADCAST または HWND_TOPMOST) の場合、すべてのアプリケーションがメッセージを処理するまで、SendMessage は新しいアプリケーションに戻りません。ただし、アプリはメッセージを送出していないため、メッセージを処理できません。そのため、新しいアプリがロックアップしてしまい、待機が成功することはありません。デッドロック。

生成されたアプリケーションを完全に制御できる場合は、SendMessage ではなく SendMessageTimeout を使用するなどの手段があります (例:DDE の開始用 (誰かがまだ使用している場合)。ただし、たとえば SetSysColors API を使用するなど、制御できない暗黙的な SendMessage ブロードキャストが発生する状況もあります。

これを回避する唯一の安全な方法は次のとおりです。

  1. Wait を別のスレッドに分割するか、
  2. Wait でタイムアウトを使用し、Wait ループで PeekMessage を使用してメッセージを確実にポンプするか、または
  3. 使用 MsgWaitForMultipleObjects API。

これは Windows 10 で動作する新しい例です。Windows10 SDK を使用する場合は、代わりに CreateProcessW を使用する必要があります。この例にはコメントが付けられており、説明がわかりやすいと思います。

#ifdef _WIN32
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <cstdlib>
#include <string>
#include <algorithm>

class process
{
public:

    static PROCESS_INFORMATION launchProcess(std::string app, std::string arg)
    {

        // Prepare handles.
        STARTUPINFO si;
        PROCESS_INFORMATION pi; // The function returns this
        ZeroMemory( &si, sizeof(si) );
        si.cb = sizeof(si);
        ZeroMemory( &pi, sizeof(pi) );

        //Prepare CreateProcess args
        std::wstring app_w(app.length(), L' '); // Make room for characters
        std::copy(app.begin(), app.end(), app_w.begin()); // Copy string to wstring.

        std::wstring arg_w(arg.length(), L' '); // Make room for characters
        std::copy(arg.begin(), arg.end(), arg_w.begin()); // Copy string to wstring.

        std::wstring input = app_w + L" " + arg_w;
        wchar_t* arg_concat = const_cast<wchar_t*>( input.c_str() );
        const wchar_t* app_const = app_w.c_str();

        // Start the child process.
        if( !CreateProcessW(
            app_const,      // app path
            arg_concat,     // Command line (needs to include app path as first argument. args seperated by whitepace)
            NULL,           // Process handle not inheritable
            NULL,           // Thread handle not inheritable
            FALSE,          // Set handle inheritance to FALSE
            0,              // No creation flags
            NULL,           // Use parent's environment block
            NULL,           // Use parent's starting directory
            &si,            // Pointer to STARTUPINFO structure
            &pi )           // Pointer to PROCESS_INFORMATION structure
        )
        {
            printf( "CreateProcess failed (%d).\n", GetLastError() );
            throw std::exception("Could not create child process");
        }
        else
        {
            std::cout << "[          ] Successfully launched child process" << std::endl;
        }

        // Return process handle
        return pi;
    }

    static bool checkIfProcessIsActive(PROCESS_INFORMATION pi)
    {
        // Check if handle is closed
            if ( pi.hProcess == NULL )
            {
                printf( "Process handle is closed or invalid (%d).\n", GetLastError());
                return FALSE;
            }

        // If handle open, check if process is active
        DWORD lpExitCode = 0;
        if( GetExitCodeProcess(pi.hProcess, &lpExitCode) == 0)
        {
            printf( "Cannot return exit code (%d).\n", GetLastError() );
            throw std::exception("Cannot return exit code");
        }
        else
        {
            if (lpExitCode == STILL_ACTIVE)
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
    }

    static bool stopProcess( PROCESS_INFORMATION &pi)
    {
        // Check if handle is invalid or has allready been closed
            if ( pi.hProcess == NULL )
            {
                printf( "Process handle invalid. Possibly allready been closed (%d).\n");
                return 0;
            }

        // Terminate Process
            if( !TerminateProcess(pi.hProcess,1))
            {
                printf( "ExitProcess failed (%d).\n", GetLastError() );
                return 0;
            }

        // Wait until child process exits.
            if( WaitForSingleObject( pi.hProcess, INFINITE ) == WAIT_FAILED)
            {
                printf( "Wait for exit process failed(%d).\n", GetLastError() );
                return 0;
            }

        // Close process and thread handles.
            if( !CloseHandle( pi.hProcess ))
            {
                printf( "Cannot close process handle(%d).\n", GetLastError() );
                return 0;
            }
            else
            {
                pi.hProcess = NULL;
            }

            if( !CloseHandle( pi.hThread ))
            {
                printf( "Cannot close thread handle (%d).\n", GetLastError() );
                return 0;
            }
            else
            {
                 pi.hProcess = NULL;
            }
            return 1;
    }
};//class process
#endif //win32
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top