> For the complete documentation index, see [llms.txt](https://krjaeh0.gitbook.io/j-log/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://krjaeh0.gitbook.io/j-log/projects/projects/allban/dev-and-deploy/dart-python.md).

# 다중 언어(Dart-Python) 프로세스 통합 및 생명주기 관리

**1. 배경: 상이한 환경의 두 엔진 통합**

* 구조: UI 및 메인 비즈니스 로직을 담당하는 Dart(Flutter) 서버가 백그라운드에서 패킷 분석을 수행하는 Python 스니퍼를 자식 프로세스(Child Process)로 생성하여 관리함.
* 핵심 과제: 부모 프로세스(서버)가 종료될 때 자식 프로세스(파이썬)와 그 자식의 자식(Tshark)까지 완벽하게 소멸시켜 시스템 자원 누수를 방지하는 것.

**2. 직면했던 기술적 난제**

가. 프로세스 트리(Process Tree) 고립 문제

* 현상: Dart의 `process.kill()` 명령은 직계 자식인 파이썬 프로세스만 종료시킴.
* 결과: 파이썬이 실행했던 하위 프로세스(Tshark.exe)가 종료되지 않고 '좀비 프로세스'로 남아 CPU 점유율을 100%까지 상승시키는 치명적인 리소스 누수 발생.

나. 표준 입출력(Stdio) 스트림의 비동기 병목

* 현상: 파이썬의 `print()` 로그가 Dart 서버 대시보드에 즉시 전달되지 않고 멈춰 있다가 프로세스가 죽을 때 한꺼번에 쏟아짐.
* 원인: 파이썬의 출력 버퍼링과 Dart 스트림 리스너 간의 동기화 문제.

***

**3. 단계별 해결 전략 및 구현 상세**

① Windows `taskkill`을 이용한 트리 종료 (Recursive Kill) 단순한 `kill()` 메서드 대신 OS 레벨의 명령어를 호출하여 프로세스 트리 전체를 소멸시키는 방식을 도입함.

* 구현: `Process.run('taskkill', ['/PID', pid.toString(), '/T', '/F'])`
  * `/T`: 자식 프로세스까지 모두 종료 (Tree Kill)
  * `/F`: 응답 없는 프로세스까지 강제 종료 (Force)

② 실시간 로그 복원을 위한 스트림 처리 파이썬의 출력을 실시간으로 감시하기 위해 데이터 흐름을 최적화함.

* Python: 실행 인자에 `-u` 플래그를 추가하여 버퍼링을 강제로 끄고 데이터를 즉시 방출.
* Dart: `LineSplitter`와 `utf8.decoder`를 결합하여 파편화되어 들어오는 바이너리 데이터를 온전한 문장 단위 로그로 복원함.

③ `runInShell: false`를 통한 경로 안정성 확보

* 문제: `runInShell: true` 사용 시 윈도우 쉘(CMD)의 간섭으로 인해 임베디드 파이썬의 실행 경로가 꼬이는 현상 발견.
* 해결: 쉘을 거치지 않고 실행 파일의 절대 경로를 직접 호출하여 경로 신뢰성을 높이고 실행 속도를 개선함.

***

**4. 향후 활용을 위한 시사점**

이 작업은 비록 현재 프로젝트의 메인 로직에서는 제외되었으나, 다음과 같은 상황에서 필수적인 해결 가이드가 됩니다.

1. 외부 엔진 연동: FFmpeg, ImageMagick 등 별도의 실행 파일(.exe)을 서버에서 제어해야 할 때.
2. 좀비 프로세스 방지: 자식 프로세스가 또 다른 하위 프로세스를 생성하는 복합적인 시스템 구축 시.
3. 리소스 최적화: 서버 종료 후에도 백그라운드 작업이 CPU를 점유하여 시스템이 느려지는 현상을 방지해야 할 때.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://krjaeh0.gitbook.io/j-log/projects/projects/allban/dev-and-deploy/dart-python.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
