Microsoft MVP성태의 닷넷 이야기
C/C++: 167. Visual C++ - 윈도우 환경에서 _execv 동작 [링크 복사], [링크+제목 복사],
조회: 5914
글쓴 사람
정성태 (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)
13752정성태10/2/20245180닷넷: 2303. C# 13 - (7) ref struct의 interface 상속 및 제네릭 제약으로 사용 가능파일 다운로드1
13751정성태10/2/20244779C/C++: 176. C/C++ - ARM64로 포팅할 때 유의할 점
13750정성태10/1/20244767C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계
13749정성태9/30/20244968닷넷: 2302. C# - ssh-keygen으로 생성한 Private Key와 Public Key 연동파일 다운로드1
13748정성태9/29/20244936닷넷: 2301. C# - BigInteger 타입이 byte 배열로 직렬화하는 방식
13747정성태9/28/20244508닷넷: 2300. C# - OpenSSH의 공개키 파일에 대한 "BEGIN OPENSSH PUBLIC KEY" / "END OPENSSH PUBLIC KEY" PEM 포맷파일 다운로드1
13746정성태9/28/20244951오류 유형: 924. Python - LocalProtocolError("Illegal header value ...")
13745정성태9/28/20244845Linux: 80. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (lldb)
13744정성태9/27/20245372닷넷: 2299. C# - Windows Hello 사용자 인증 다이얼로그 표시하기파일 다운로드1
13743정성태9/26/20245532닷넷: 2298. C# - Console 프로젝트에서의 await 대상으로 Main 스레드 활용하는 방법 [1]
13742정성태9/26/20246010닷넷: 2297. C# - ssh-keygen으로 생성한 ecdsa 유형의 Public Key 파일 해석 [1]파일 다운로드1
13741정성태9/25/20245054디버깅 기술: 202. windbg - ASP.NET MVC Web Application (.NET Framework) 응용 프로그램의 덤프 분석 시 요령
13740정성태9/24/20245094기타: 86. RSA 공개키 등의 modulus 값에 0x00 선행 바이트가 있는 이유(ASN.1 인코딩)
13739정성태9/24/20245096닷넷: 2297. C# - ssh-keygen으로 생성한 Public Key 파일 해석과 fingerprint 값(md5, sha256) 생성 [1]파일 다운로드1
13738정성태9/22/20244895C/C++: 174. C/C++ - 윈도우 운영체제에서의 file descriptor, FILE*파일 다운로드1
13737정성태9/21/20245135개발 환경 구성: 727. Visual C++ - 리눅스 프로젝트를 위한 빌드 서버의 msbuild 구성
13736정성태9/20/20244998오류 유형: 923. Visual Studio Code - Could not establish connection to "...": Port forwarding is disabled.
13735정성태9/20/20245333개발 환경 구성: 726. ARM 플랫폼용 Visual C++ 리눅스 프로젝트 빌드
13734정성태9/19/20245172개발 환경 구성: 725. ssh를 이용한 원격 docker 서비스 사용
13733정성태9/19/20245262VS.NET IDE: 194. Visual Studio - Cross Platform / "Authentication Type: Private Key"로 접속하는 방법
13732정성태9/17/20245463개발 환경 구성: 724. ARM + docker 환경에서 .NET 8 설치
13731정성태9/15/20245942개발 환경 구성: 723. C# / Visual C++ - Control Flow Guard (CFG) 활성화 [1]파일 다운로드2
13730정성태9/10/20245406오류 유형: 922. docker - RULE_APPEND failed (No such file or directory): rule in chain DOCKER
13729정성태9/9/20246170C/C++: 173. Windows / C++ - AllocConsole로 할당한 콘솔과 CRT 함수 연동 [1]파일 다운로드1
13728정성태9/7/20245988C/C++: 172. Windows - C 런타임에서 STARTUPINFO의 cbReserved2, lpReserved2 멤버를 사용하는 이유파일 다운로드1
13727정성태9/6/20246275개발 환경 구성: 722. ARM 플랫폼 빌드를 위한 미니 PC(?) - Khadas VIM4 [1]
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...