0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CretateProcess()で標準出力をファイル出力

Last updated at Posted at 2023-11-07
sample.c
#include <windows.h>


int _tmain(int argc, _TCHAR* argv[])
{
    // 子プロセスが親プロセスから開いているハンドルを継承できるようにする
    SECURITY_ATTRIBUTES sa;
    sa.nLength              = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle       = TRUE;   
    
    HANDLE h1 = CreateFile(_T("out.log"),
        FILE_APPEND_DATA,    // ファイルを追記モードで開く
        FILE_SHARE_WRITE | FILE_SHARE_READ,  // 後からファイルを開くプロセスは読込と書込みを許可
        &sa,    // 継承しなくてよい場合は NULL で良いらしい
        OPEN_ALWAYS,   // ファイルがあれば開く、なければ作る
        FILE_ATTRIBUTE_NORMAL,    // 通常ファイルとして作成
        NULL );

    PROCESS_INFORMATION pi; 
    STARTUPINFO si;
    BOOL ret = FALSE; 
    DWORD flags = CREATE_NO_WINDOW;

    ZeroMemory( &pi, sizeof(PROCESS_INFORMATION) );
    ZeroMemory( &si, sizeof(STARTUPINFO) );
    si.cb = sizeof(STARTUPINFO); 
    si.dwFlags |= STARTF_USESTDHANDLES;
    si.hStdInput = NULL;
    si.hStdOutput = h1;   // 標準出力をリダイレクト
    si.hStdError = h1;    // 標準エラー出力をリダイレクト

    TCHAR cmd[]= TEXT("Test.exe 30");
    ret = CreateProcess(NULL, cmd, NULL, NULL, TRUE, flags, NULL, NULL, &si, &pi);

    if ( ret ) 
    {
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        return 0;
    }

    return -1;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?