Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [링크 복사], [링크+제목 복사],
조회: 14113
글쓴 사람
정성태 (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)
13754정성태10/4/20246781닷넷: 2304. C# 13 - (8) 부분 메서드 정의를 속성 및 인덱서에도 확대파일 다운로드1
13753정성태10/4/20246433Linux: 81. Linux - PATH 환경변수의 적용 규칙
13752정성태10/2/20247643닷넷: 2303. C# 13 - (7) ref struct의 interface 상속 및 제네릭 제약으로 사용 가능 [6]파일 다운로드1
13751정성태10/2/20246211C/C++: 176. C/C++ - ARM64로 포팅할 때 유의할 점
13750정성태10/1/20246057C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계
13749정성태9/30/20246225닷넷: 2302. C# - ssh-keygen으로 생성한 Private Key와 Public Key 연동파일 다운로드1
13748정성태9/29/20246673닷넷: 2301. C# - BigInteger 타입이 byte 배열로 직렬화하는 방식
13747정성태9/28/20247327닷넷: 2300. C# - OpenSSH의 공개키 파일에 대한 "BEGIN OPENSSH PUBLIC KEY" / "END OPENSSH PUBLIC KEY" PEM 포맷파일 다운로드1
13746정성태9/28/20246509오류 유형: 924. Python - LocalProtocolError("Illegal header value ...")
13745정성태9/28/20246375Linux: 80. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (lldb)
13744정성태9/27/20246883닷넷: 2299. C# - Windows Hello 사용자 인증 다이얼로그 표시하기파일 다운로드1
13743정성태9/26/20247560닷넷: 2298. C# - Console 프로젝트에서의 await 대상으로 Main 스레드 활용하는 방법 [1]
13742정성태9/26/20247598닷넷: 2297. C# - ssh-keygen으로 생성한 ecdsa 유형의 Public Key 파일 해석 [1]파일 다운로드1
13741정성태9/25/20246932디버깅 기술: 202. windbg - ASP.NET MVC Web Application (.NET Framework) 응용 프로그램의 덤프 분석 시 요령
13740정성태9/24/20246566기타: 86. RSA 공개키 등의 modulus 값에 0x00 선행 바이트가 있는 이유(ASN.1 인코딩)
13739정성태9/24/20246838닷넷: 2297. C# - ssh-keygen으로 생성한 Public Key 파일 해석과 fingerprint 값(md5, sha256) 생성 [1]파일 다운로드1
13738정성태9/22/20246525C/C++: 174. C/C++ - 윈도우 운영체제에서의 file descriptor, FILE*파일 다운로드1
13737정성태9/21/20247037개발 환경 구성: 727. Visual C++ - 리눅스 프로젝트를 위한 빌드 서버의 msbuild 구성
13736정성태9/20/20247060오류 유형: 923. Visual Studio Code - Could not establish connection to "...": Port forwarding is disabled.
13735정성태9/20/20246804개발 환경 구성: 726. ARM 플랫폼용 Visual C++ 리눅스 프로젝트 빌드
13734정성태9/19/20246475개발 환경 구성: 725. ssh를 이용한 원격 docker 서비스 사용
13733정성태9/19/20246978VS.NET IDE: 194. Visual Studio - Cross Platform / "Authentication Type: Private Key"로 접속하는 방법
13732정성태9/17/20247124개발 환경 구성: 724. ARM + docker 환경에서 .NET 8 설치
13731정성태9/15/20247645개발 환경 구성: 723. C# / Visual C++ - Control Flow Guard (CFG) 활성화 [1]파일 다운로드2
13730정성태9/10/20248023오류 유형: 922. docker - RULE_APPEND failed (No such file or directory): rule in chain DOCKER
13729정성태9/9/20248888C/C++: 173. Windows / C++ - AllocConsole로 할당한 콘솔과 CRT 함수 연동 [1]파일 다운로드1
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...