Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [링크 복사], [링크+제목 복사],
조회: 13843
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - Job에 Process 포함하는 방법

개인적으로 단 한 번도 Job을 생성한 프로젝트를 해 본 적이 없는데요, 아마도 마이크로소프트 이외에는 거의 안 쓰는 커널 자원이지 않을까... 싶습니다. ^^ (혹시, 사용하고 계신 분 있으시면 어떤 상황에서 쓰시고 계신지 덧글 부탁드립니다.)

마침 oldnewthing 블로그에 Job과 관련한 글이 올라왔는데요,

A more direct and mistake-free way of creating a process in a job object
; https://devblogs.microsoft.com/oldnewthing/20230209-00/?p=107812

Windows 10/Windows Server 2016 미만의 운영체제에서는 Job에 프로세스를 할당하는 과정이 이렇게 된다고 합니다.

  1. 프로세스를 suspend 상태로 생성
  2. Assign­Process­To­Job­Object API를 사용해 Job에 프로세스 연결
  3. 중지시켰던 프로세스를 resume

문제는, 1번 과정을 수행 후 2번 과정으로 넘어가는 중에 현재의 프로세스가 종료해 버리면 suspend 상태로 실행해 두었던 프로세스가 붕 떠버리는(orphaning the process) 결과가 발생한다는 겁니다.

이런 문제를 해결하기 위해 "PROC_THREAD_ATTRIBUTE_JOB_LIST" 옵션이 추가되었고, 이를 활용하면 프로세스를 생성하는 시점에 Job에 할당하는 것이 가능합니다. 본문에서는 그에 대한 C/C++ 코드가 실려 있는데요, C#으로는 다음과 같이 변경할 수 있습니다.

// ...[생략: 전체 소스 코드는 첨부 파일을 확인하세요.]...

static void Main(string[] args)
{
    IntPtr job = CreateJobObject(IntPtr.Zero, null);

    nint size = 0;
    InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size);
    nint p = Marshal.AllocHGlobal(size);

    InitializeProcThreadAttributeList(p, 1, 0, ref size);

    nuint flags = ProcThreadAttributeValue(ProcThreadAttributeJobList, false, true, false);
    bool result = UpdateProcThreadAttribute(p, 0, flags, ref job, IntPtr.Size, IntPtr.Zero, IntPtr.Zero);

    string cmd = "C:\\Windows\\System32\\cmd.exe";
    STARTUPINFOEX siex = new STARTUPINFOEX();
    siex.lpAttributeList = p;
    siex.StartupInfo.cb = Marshal.SizeOf<STARTUPINFOEX>();
    PROCESS_INFORMATION pi;

    CreateProcess(cmd, cmd, IntPtr.Zero, IntPtr.Zero, false, CREATE_NEW_CONSOLE | EXTENDED_STARTUPINFO_PRESENT,
        IntPtr.Zero, null, ref siex, out pi);

    bool isInJob;
    IsProcessInJob(pi.hProcess, job, out isInJob);
    Console.WriteLine($"In job: {isInJob}");

    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    Marshal.FreeHGlobal(p);

    CloseHandle(job);
}

Job과 관련한 기능은 닷넷 런타임의 범위에는 속하지 않으므로 모든 API를 P/Invoke로 연결해 호출해야 합니다. 또한, C#의 ProcessStartInfo는 lpAttributeList를 설정할 수 있는 옵션을 제공하지 않아 STARTUPINFOEX/CreateProcess까지도 모두 P/Invoke로 호출해야 하고!

어쨌든 저 코드를 실행하면 화면에는 "In job: True"라는 문자열이 출력되고, Visual Studio에서 그 라인에 BP로 멈춰 Process Explorer를 통해 확인해 보면 cmd.exe 프로세스가 Job에 속해 있는 것을 볼 수 있습니다.

cs_createjob_1.png

(첨부 파일은 이 글의 예제 코드를 포함합니다.)





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







[최초 등록일: ]
[최종 수정일: 2/13/2023]

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

비밀번호

댓글 작성자
 



2023-03-23 07시53분
Why does the usage of the initial registers of a Win32 process depend on whether it is a 32-bit or 64-bit process?
; https://devblogs.microsoft.com/oldnewthing/20230321-00/?p=107954
정성태
2025-05-27 10시22분
How can I detect if one of my helper processes is launching child processes?
; https://devblogs.microsoft.com/oldnewthing/20250523-00/?p=111216

Job에 할당한 프로세스의 경우, 그 프로세스에서 생성한 자식 프로세스의 생성/종료를 IOCP를 이용해 알림을 받을 수 있다고 합니다.

#define UNICODE
#define _UNICODE
#define STRICT
#include <windows.h>
#include <stdio.h>
#include <atlbase.h>
#include <atlalloc.h>
#include <shlwapi.h>

int __cdecl wmain(int argc, PWSTR argv[])
{
 CHandle Job(CreateJobObject(nullptr, nullptr));
 if (!Job) {
  wprintf(L"CreateJobObject, error %d\n", GetLastError());
  return 0;
 }


 CHandle IOPort(CreateIoCompletionPort(INVALID_HANDLE_VALUE,
                                       nullptr, 0, 1));
 if (!IOPort) {
  wprintf(L"CreateIoCompletionPort, error %d\n",
          GetLastError());
  return 0;
 }


 JOBOBJECT_ASSOCIATE_COMPLETION_PORT Port;
 Port.CompletionKey = Job;
 Port.CompletionPort = IOPort;
 if (!SetInformationJobObject(Job,
       JobObjectAssociateCompletionPortInformation,
       &Port, sizeof(Port))) {
  wprintf(L"SetInformation, error %d\n", GetLastError());
  return 0;
 }


 PROCESS_INFORMATION ProcessInformation;
 STARTUPINFO StartupInfo = { sizeof(StartupInfo) };
 PWSTR CommandLine = PathGetArgs(GetCommandLine());


 if (!CreateProcess(nullptr, CommandLine, nullptr, nullptr,
                    FALSE, CREATE_SUSPENDED, nullptr, nullptr,
                    &StartupInfo, &ProcessInformation)) {
  wprintf(L"CreateProcess, error %d\n", GetLastError());
  return 0;
 }


 if (!AssignProcessToJobObject(Job,
         ProcessInformation.hProcess)) {
  wprintf(L"Assign, error %d\n", GetLastError());
  return 0;
 }


 ResumeThread(ProcessInformation.hThread);
 CloseHandle(ProcessInformation.hThread);
 CloseHandle(ProcessInformation.hProcess);


 DWORD CompletionCode;
 ULONG_PTR CompletionKey;
 LPOVERLAPPED Overlapped;

 while (GetQueuedCompletionStatus(IOPort, &CompletionCode,
          &CompletionKey, &Overlapped, INFINITE)) {
  if ((HANDLE)CompletionKey == Job) {
    if (CompletionCode == JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO) {
      break; // all processes have exited - done
    } else if (CompletionCode == JOB_OBJECT_MSG_NEW_PROCESS) {
      wprintf(L"Process %d created\n", PtrToInt(Overlapped));
    } else if (CompletionCode == JOB_OBJECT_MSG_EXIT_PROCESS) {
      wprintf(L"Process %d exited\n", PtrToInt(Overlapped));
    } else if (CompletionCode == JOB_OBJECT_MSG_ABNORMAL_NEW_PROCESS) {
      wprintf(L"Process %d exited abnormally\n", PtrToInt(Overlapped));
    }
  }
 }

 wprintf(L"All done\n");

 return 0;
}
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13945정성태6/7/2025454오류 유형: 960. 파이썬 + conda - mysqlclient 사용 시 "NameError: name '_mysql' is not defined" 에러
13944정성태6/7/2025475오류 유형: 959. The trust relationship between this workstation and the primary domain failed. - 네 번째 이야기
13943정성태6/6/2025697개발 환경 구성: 748. Windows + Foundry Local - 로컬에서 AI 모델 활용
13942정성태6/5/2025882오류 유형: 958. winget 설치 시 "0x80d02002 : unknown error"
13941정성태6/2/20251034닷넷: 2334. C# - cpuid 명령어를 이용한 CPU 제조사 문자열 가져오기파일 다운로드1
13940정성태6/1/20251419C/C++: 188. C++의 32비트 + Release 어셈블리 코드를 .NET으로 포팅할 때 주의할 점파일 다운로드1
13939정성태5/29/20251709오류 유형: 957. NVIDIA Triton Inference Server - version `GLIBCXX_3.4.32' not found (required by /opt/tritonserver/backends/python/triton_python_backend_stub)
13938정성태5/29/20251435개발 환경 구성: 747. 파이썬 - WSL/docker에 구성한 Triton 예제 개발 환경
13937정성태5/24/20251359개발 환경 구성: 746. Windows + WSL2 환경에서 (tensorflow 등의) NVIDIA GPU 인식
13936정성태5/23/20251188개발 환경 구성: 745. Linux / WSL 환경에 Miniconda 설치하기
13935정성태5/20/20251233파이썬 - pip 사용 시 "ImportError: cannot import name 'html5lib' from 'pip._vendor'" 오류
13934정성태5/20/20251712스크립트: 77. 파이썬 - 'urllib.request' 모듈의 명시적/암시적 로딩 차이
13933정성태5/19/20251290오류 유형: 956. Visual Studio 2022가 17.12 버전부터 업데이트 되지 않는다면?
13932정성태5/18/20251501스크립트: 76. 파이썬 - Version 문자열 다루기(semver 패키지)
13931정성태5/17/20251793스크립트: 75. 파이썬 - Cython 기본 예제 및 컴파일
13930정성태5/17/20251491개발 환경 구성: 744. 파이썬 - Windows embeddable package 환경에서 외부 패키지 사용하는 방법(ex: UFO² 환경 구성)
13929정성태5/16/20251516오류 유형: 955. 파이썬 - "Windows embeddable package" REPL 환경에서 "NameError: name 'exit' is not defined"
13928정성태5/15/20251558오류 유형: 954. UFO² - "'Invalid URL (POST /v1/chat/completions/chat/completions)'"
13927정성태5/15/20251545오류 유형: 953. OpenAI - The API request of HOST_AGENT failed: OpenAI API request exceeded rate limit: Error code: 429
13926정성태5/14/20251907개발 환경 구성: 743. LLM과 윈도우의 만남 - Desktop AgentOS UFO² 기본 환경 구성
13925정성태5/12/20252009닷넷: 2333. C# - (Console 유형의 프로젝트에서) Clipboard 연동파일 다운로드1
13924정성태5/8/20251759닷넷: 2332. C# - (JetBrains Omea Reader 대상으로) 런타임 시에 메서드 가로채기 [2]파일 다운로드1
13923정성태5/5/20251504스크립트: 74. 파이썬 - C# - Python.NET의 RunSimpleScript, Exec, Eval 차이점파일 다운로드1
13922정성태5/3/20251757스크립트: 73. 파이썬 - Windows embeddable package 버전에서 tkinter 환경 구성
13921정성태5/3/20252282오류 유형: 952. 듀얼 채널 메모리 정렬을 지키지 않은 컴퓨터의 Windows 비정상 종료 현상(Blue Screen) [2]
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...