Microsoft MVP성태의 닷넷 이야기
C/C++: 167. Visual C++ - 윈도우 환경에서 _execv 동작 [링크 복사], [링크+제목 복사],
조회: 6745
글쓴 사람
정성태 (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)
13843정성태12/13/20244368오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
13842정성태12/12/20244510디버깅 기술: 205. Windbg - KPCR, KPRCB
13841정성태12/11/20244843오류 유형: 937. error MSB4044: The "ValidateValidArchitecture" task was not given a value for the required parameter "RemoteTarget"
13840정성태12/11/20244417오류 유형: 936. msbuild - Your project file doesn't list 'win' as a "RuntimeIdentifier"
13839정성태12/11/20244841오류 유형: 936. msbuild - error CS1617: Invalid option '12.0' for /langversion. Use '/langversion:?' to list supported values.
13838정성태12/4/20244583오류 유형: 935. Windbg - Breakpoint 0's offset expression evaluation failed.
13837정성태12/3/20245037디버깅 기술: 204. Windbg - 윈도우 핸들 테이블 (3) - Windows 10 이상인 경우
13836정성태12/3/20244610디버깅 기술: 203. Windbg - x64 가상 주소를 물리 주소로 변환 (페이지 크기가 2MB인 경우)
13835정성태12/2/20245040오류 유형: 934. Azure - rm: cannot remove '...': Directory not empty
13834정성태11/29/20245267Windows: 275. C# - CUI 애플리케이션과 Console 윈도우 (Windows 10 미만의 Classic Console 모드인 경우) [1]파일 다운로드1
13833정성태11/29/20244953개발 환경 구성: 737. Azure Web App에서 Scale-out으로 늘어난 리눅스 인스턴스에 SSH 접속하는 방법
13832정성태11/27/20244899Windows: 274. Windows 7부터 도입한 conhost.exe
13831정성태11/27/20244368Linux: 111. eBPF - BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_MAP_TYPE_RINGBUF에 대한 다양한 용어들
13830정성태11/25/20245169개발 환경 구성: 736. 파이썬 웹 앱을 Azure App Service에 배포하기
13829정성태11/25/20245133스크립트: 67. 파이썬 - Windows 버전에서 함께 설치되는 py.exe
13828정성태11/25/20244427개발 환경 구성: 735. Azure - 압축 파일을 이용한 web app 배포 시 디렉터리 구분이 안 되는 문제파일 다운로드1
13827정성태11/25/20245076Windows: 273. Windows 환경의 파일 압축 방법 (tar, Compress-Archive)
13826정성태11/21/20245309닷넷: 2313. C# - (비밀번호 등의) Console로부터 입력받을 때 문자열 출력 숨기기(echo 끄기)파일 다운로드1
13825정성태11/21/20245648Linux: 110. eBPF / bpf2go - BPF_RINGBUF_OUTPUT / BPF_MAP_TYPE_RINGBUF 사용법
13824정성태11/20/20244742Linux: 109. eBPF / bpf2go - BPF_PERF_OUTPUT / BPF_MAP_TYPE_PERF_EVENT_ARRAY 사용법
13823정성태11/20/20245273개발 환경 구성: 734. Ubuntu에 docker, kubernetes (k3s) 설치
13822정성태11/20/20245135개발 환경 구성: 733. Windbg - VirtualBox VM의 커널 디버거 연결 시 COM 포트가 없는 경우
13821정성태11/18/20245065Linux: 108. Linux와 Windows의 프로세스/스레드 ID 관리 방식
13820정성태11/18/20245232VS.NET IDE: 195. Visual C++ - C# 프로젝트처럼 CopyToOutputDirectory 항목을 추가하는 방법
13819정성태11/15/20244477Linux: 107. eBPF - libbpf CO-RE의 CONFIG_DEBUG_INFO_BTF 빌드 여부에 대한 의존성
13818정성태11/15/20245246Windows: 272. Windows 11 24H2 - sudo 추가
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...