Microsoft MVP성태의 닷넷 이야기
C/C++: 167. Visual C++ - 윈도우 환경에서 _execv 동작 [링크 복사], [링크+제목 복사],
조회: 5866
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 3개 있습니다.)
Linux: 44. 윈도우 개발자를 위한 리눅스 fork 동작 방식 설명 (파이썬 코드)
; https://www.sysnet.pe.kr/2/0/12811

스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작
; https://www.sysnet.pe.kr/2/0/12843

C/C++: 167. Visual C++ - 윈도우 환경에서 _execv 동작
; https://www.sysnet.pe.kr/2/0/13716




Visual C++ - 윈도우 환경에서 _execv 동작

Windows의 CreateProcess 기능을 리눅스에서는 fork + exec로 표현할 수 있습니다.

그리고 exec... 계열의 함수는 자신의 프로세스 공간에 대상 프로그램을 로딩하는 건데요, 재미있는 건 Visual C++의 CRT 함수에도 동일한 이름의 함수들이 제공됩니다.

하지만, 당연히 리눅스처럼 현재 프로세스 공간에 이미지를 로드하지는 못하고, 대신 자식 프로세스를 생성하는 식으로 우회합니다. 재미있는 건, 이 함수의 사용법인데요, 예를 들어 _execv 함수로,

_execv, _wexecv
; https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/execv-wexecv

다음과 같이 코딩을 할 수 있을 텐데요,

#include <iostream>
#include <process.h>
#include <Windows.h>

#pragma comment(lib, "Shlwapi.lib")

int main(int argc, char** argv)
{
    const char* const argMark[] = {
          "1",
          0 };

    if (argc == 1) // 인자가 1개인 경우에만, 즉 최초 실행했을 때만 자신을 다시 실행
    {
        char path[4096] = { 0 };
        GetModuleFileNameA(nullptr, path, 4096);

        auto result = _execv(path, argMark);
        if (result == -1)
        {
            std::cout << "result: " << errno << "\n";
        }
    }

    std::cout << "Hello World!\n";
}

하지만, 위의 프로그램을 실행하면 errno 값이 12(ENOMEM)로 나오면서 실패합니다. 이유는, 2번째 인자에 넘겨주는 값(위의 경우 argMark)의 형식이, 자신의 경로를 [0]번째 인자에 포함시키는 형식으로 전달해야 하기 때문입니다.

그러니까, 위에서처럼 정말 "1" 인자만 전달한 경우에는 argc 값이 1이 되므로 CreateProcess를 무한정 반복해 말 그대로 ENOMEM 오류가 발생하는 것입니다. 결국, 위의 코드는 아래와 같이 수정해야 합니다.

char path[4096] = { 0 };
GetModuleFileNameA(nullptr, path, 4096);

const char* const argMark[] = { path, "1", 0 };

_execv(path, argMark);

참고로, 윈도우 환경에서의 exec... 함수들은 마치 자신의 프로세스 공간에 이미지를 로드하는 것처럼 흉내 내기 위해 저 함수를 성공적으로 실행한 경우에는 호출 측 프로세스가 바로 종료합니다.




기왕 해본 김에, _execv 함수의 구현을 따라가 볼까요?

// C:\Program Files (x86)\Windows Kits\10\Source\10.0.22621.0\ucrt\exec\spawnv.cpp

extern "C" intptr_t __cdecl _execv(
    char const*        const file_name,
    char const* const* const arguments
    )
{
    return common_spawnv(_P_OVERLAY, file_name, arguments, static_cast<char const* const*>(nullptr));
}

template <typename Character>
static intptr_t __cdecl common_spawnv(
    int                     const mode,
    Character const*        const file_name,
    Character const* const* const arguments,
    Character const* const* const environment
    ) throw()
{
    // ...[생략]...

    if (traits::tcsrchr(end_of_directory, '.'))
    {
        // If an extension was provided, just invoke the path:
        if (traits::taccess_s(mutated_file_name, 0) == 0)
        {
            return execute_command(mode, mutated_file_name, arguments, environment);
        }
    }
    else
    {
        // ...[생략]...
    }

    return -1;
}

보는 바와 같이 common_spawnv는 약간의 validation 과정을 거친 후 execute_command로 전달하는데,

// C:\Program Files (x86)\Windows Kits\10\Source\10.0.10240.0\ucrt\exec\spawnv.cpp

// Spawns a child process.  The mode must be one of the _P-modes from <process.h>.
// The return value depends on the mode:
// * _P_OVERLAY:  On success, calls _exit() and does not return. Returns -1 on failure.
// * _P_WAIT:     Returns (termination_code << 8 + result_code)
// * _P_DETACH:   Returns 0 on success; -1 on failure
// * Others:      Returns a handle to the process. The caller must close the handle.
template <typename Character>
static intptr_t __cdecl execute_command(
    int                     const mode,
    Character const*        const file_name,
    Character const* const* const arguments,
    Character const* const* const environment
    ) throw()
{
    // ...[생략]...

    __crt_unique_heap_ptr<BYTE> handle_data;
    size_t                      handle_data_size;
    if (!accumulate_inheritable_handles(handle_data.get_address_of(), &handle_data_size, mode != _P_DETACH))
        return -1;

    DWORD creation_flags = 0;
    if (mode == _P_DETACH)
        creation_flags |= DETACHED_PROCESS;

    if (should_create_unicode_environment(Character()))
        creation_flags |= CREATE_UNICODE_ENVIRONMENT;

    _doserrno = 0;

    STARTUPINFOW startup_info = { };
    startup_info.cb          = sizeof(startup_info);
    startup_info.cbReserved2 = static_cast<WORD>(handle_data_size);
    startup_info.lpReserved2 = handle_data.get();

    PROCESS_INFORMATION process_info;
    BOOL const create_process_status = traits::create_process(
        const_cast<Character*>(file_name),
        command_line.get(),
        nullptr,
        nullptr,
        TRUE,
        creation_flags,
        environment_block.get(),
        nullptr,
        &startup_info,
        &process_info);

    __crt_unique_handle process_handle(process_info.hProcess);
    __crt_unique_handle thread_handle(process_info.hThread);

    if (!create_process_status)
    {
        __acrt_errno_map_os_error(GetLastError());
        return -1;
    }

    if (mode == _P_OVERLAY)
    {
        // Destroy ourselves:
        _exit(0);
    }
    else if (mode == _P_WAIT)
    {
        WaitForSingleObject(process_info.hProcess, static_cast<DWORD>(-1));

        // ...[생략]...
    }
    else if (mode == _P_DETACH)
    {
        /* like totally detached asynchronous spawn, dude,
            close process handle, return 0 for success */
        return 0;
    }
    else
    {
        // Asynchronous spawn:  return process handle:
        return reinterpret_cast<intptr_t>(process_handle.detach());
    }
}

이때 execute_command의 첫 번째 mode 인자에 따라,

1) _P_OVERLAY인 경우, 호출 측, 즉 부모를 exit(0) 함수로 종료하거나 2) _P_WAIT인 경우 자식 프로세스의 종료까지 대기하거나, 3) _P_DETACH인 경우 곧바로 반환을 합니다.

exec... 함수는 저 모드가 무조건 _P_OVERLAY로 고정된 반면 spawn... 계열 함수들은 mode를 선택할 수 있습니다. 일례로,

_spawnv, _wspawnv
; https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/spawnv-wspawnv

intptr_t _spawnv(
   int mode,
   const char *cmdname,
   const char *const *argv
);
intptr_t _wspawnv(
   int mode,
   const wchar_t *cmdname,
   const wchar_t *const *argv
);

저 함수들의 mode로 가능한 값이 _P_OVERLAY, _P_WAIT, _P_DETACH인 것입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/21/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2025-01-24 11시34분
Linux의 경우 Shell Script에서도 exec 명령어를 통해 현재의 shell 프로세스를 대상 프로세스로 교체하는 기능을 제공합니다.

$ exec --help
exec: exec [-cl] [-a name] [command [arguments ...]] [redirection ...]
    Replace the shell with the given command.

    Execute COMMAND, replacing this shell with the specified program.
    ARGUMENTS become the arguments to COMMAND. If COMMAND is not specified,
    any redirections take effect in the current shell.

    Options:
      -a name pass NAME as the zeroth argument to COMMAND
      -c execute COMMAND with an empty environment
      -l place a dash in the zeroth argument to COMMAND

    If the command cannot be executed, a non-interactive shell exits, unless
    the shell option `execfail' is set.

    Exit Status:
    Returns success unless COMMAND is not found or a redirection error occurs.
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13901정성태3/9/2025831Windows: 280. Hyper-V의 3가지 Thread Scheduler (Classic, Core, Root)
13900정성태3/8/20251025스크립트: 72. 파이썬 - SQLAlchemy + oracledb 연동
13899정성태3/7/20251107스크립트: 71. 파이썬 - asyncio의 ContextVar 전달
13898정성태3/5/20251154오류 유형: 948. Visual Studio - Proxy Authentication Required: dotnetfeed.blob.core.windows.net
13897정성태3/5/20251127닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)파일 다운로드1
13896정성태3/5/20251137Windows: 279. Hyper-V Manager - VM 목록의 CPU Usage 항목이 항상 0%로 나오는 문제
13895정성태3/4/20251265Linux: 117. eBPF / bpf2go - Map에 추가된 요소의 개수를 확인하는 방법
13894정성태2/28/20251389Linux: 116. eBPF / bpf2go - BTF Style Maps 정의 구문과 데이터 정렬 문제
13893정성태2/27/20251396Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
13892정성태2/24/20251461닷넷: 2325. C# - PowerShell과 연동하는 방법파일 다운로드1
13891정성태2/23/20251432닷넷: 2324. C# - 프로세스의 성능 카운터용 인스턴스 이름을 구하는 방법파일 다운로드1
13890정성태2/21/20251430닷넷: 2323. C# - 프로세스 메모리 중 Private Working Set 크기를 구하는 방법(Win32 API)파일 다운로드1
13889정성태2/20/20251602닷넷: 2322. C# - 프로세스 메모리 중 Private Working Set 크기를 구하는 방법(성능 카운터, WMI) [1]파일 다운로드1
13888정성태2/17/20251363닷넷: 2321. Blazor에서 발생할 수 있는 async void 메서드의 부작용
13887정성태2/17/20251371닷넷: 2320. Blazor의 razor 페이지에서 code-behind 파일로 코드를 분리하는 방법
13886정성태2/15/20251438VS.NET IDE: 196. Visual Studio - Code-behind처럼 cs 파일을 그룹핑하는 방법
13885정성태2/14/20251432닷넷: 2319. ASP.NET Core Web API / Razor 페이지에서 발생할 수 있는 async void 메서드의 부작용
13884정성태2/13/20251845닷넷: 2318. C# - (async Task가 아닌) async void 사용 시의 부작용파일 다운로드1
13883정성태2/12/20251787닷넷: 2317. C# - Memory Mapped I/O를 이용한 PCI Configuration Space 정보 열람파일 다운로드1
13882정성태2/10/20251946스크립트: 70. 파이썬 - oracledb 패키지 연동 시 Thin / Thick 모드
13881정성태2/7/20252055닷넷: 2316. C# - Port I/O를 이용한 PCI Configuration Space 정보 열람파일 다운로드1
13880정성태2/5/20251842오류 유형: 947. sshd - Failed to start OpenSSH server daemon.
13879정성태2/5/20252048오류 유형: 946. Ubuntu - N: Updating from such a repository can't be done securely, and is therefore disabled by default.
13878정성태2/3/20252051오류 유형: 945. Windows - 최대 절전 모드 시 DRIVER_POWER_STATE_FAILURE 발생 (pacer.sys)
13877정성태1/25/20252247닷넷: 2315. C# - PCI 장치 열거 (레지스트리, SetupAPI)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...