부모 프로세스가 자식 프로세스를 시작하면 명령 줄 인수를 통해 부모 프로세스 ID를 자식에게 전달합니다.
그런 다음 하위 프로세스에서 Process.GetProcessById(int)
을 사용하여 상위 프로세스를 가져오고 Process.WaitForExit()
을 사용하십시오. 또는 Process.Exited
이벤트를 사용하여 상위 프로세스가 종료 될 때 알림을받습니다. Process.EnableRaisingEvents
을 true
으로 설정해야합니다. 그렇지 않으면 이벤트가 발생하지 않습니다.
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static AutoResetEvent _autoResetEvent;
static void Main(string[] args)
{
int parentProcessId = int.Parse(args[0]);
_autoResetEvent = new AutoResetEvent(false);
WaitCallback callback = delegate(object processId) { CheckProcess((int)processId); };
ThreadPool.QueueUserWorkItem(callback, parentProcessId);
_autoResetEvent.WaitOne();
}
static void CheckProcess(int processId)
{
try
{
Process process = Process.GetProcessById(processId);
process.WaitForExit();
Console.WriteLine("Process [{0}] exited.", processId);
}
catch (ArgumentException)
{
Console.WriteLine("Process [{0}] not running.", processId);
}
_autoResetEvent.Set();
}
}
Process.Exited
이벤트를 사용하여 다음과 같이 할 수있다 :
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static AutoResetEvent _autoResetEvent;
static void Main(string[] args)
{
int parentProcessId = int.Parse(args[0]);
Process process = Process.GetProcessById(parentProcessId);
process.EnableRaisingEvents = true;
process.Exited += new EventHandler(process_Exited);
_autoResetEvent = new AutoResetEvent(false);
_autoResetEvent.WaitOne();
}
static void process_Exited(object sender, EventArgs e)
{
Console.WriteLine("Process exit event triggered.");
_autoResetEvent.Set();
}
}
다음
음은 ... 보통은 부모 프로세스입니다. 프로세스의 성을 실제로 인식하지 않는 한. 건배. –
@AOI Karasu : LOL, 좋은 지적, 나는 그것을 바꾸기 위해 자유를 취했다 (성이 중요하다면, 나의 변화, Night Walker를 되 돌리십시오). – Abel
.NET 용 하위 프로세스 라이브러리를 방금 게시했습니다. http://childprocess.codeplex.com/ –