---
title: "delphi 双进程守护 "
author: "cfeers"
date: "2011-05-12T17:04:40Z"
tags: ["Delphi", "Windows", "工作"]
categories: ["编程语言"]
slug: "delphi"
draft: false
lastmod: "2011-05-12T17:04:40Z"
id: 1041557
url: "https://cfeers.iteye.com/blog/1041557"
---

这是一个关于父亲与儿子的故事：

父亲的一生：①生一个儿子。如果儿子被杀了，再生一个！  
             ②工作。

儿子的一生：等着父亲被杀，取而代之（成为父亲）。

这则故事已经完整地表达了我想要表达的全部思想，我们可以通过假设“父亲被杀了”或“儿子被杀了”来领会它。

废话少说，看源码：

program Oliver;

uses  
   Windows;

procedure WaitForAncestor;  
var  
   MutexName: String;  
   MutexHandle: THandle;  
begin  
   MutexName := '110';  
   MutexHandle := OpenMutex(SYNCHRONIZE, True, PChar(MutexName));  
   if (MutexHandle &lt;&gt; 0) then  
   begin  
     WaitForSingleObject(MutexHandle, INFINITE);  
     CloseHandle(MutexHandle);  
   end;  
   CreateMutex(nil, True, PChar(MutexName));  
end;

procedure RunSuccessor;  
var  
   StartupInfo: TStartupInfo;  
   ProcessInfo: TProcessInformation;  
begin  
   while (True) do  
   begin  
     CreateProcess(PChar(ParamStr(0)), nil, nil, nil, True, NORMAL\_PRIORITY\_CLASS, nil, nil, StartupInfo, ProcessInfo);  
     WaitForSingleObject(ProcessInfo.hProcess, INFINITE);  
   end;  
end;

begin  
   WaitForAncestor;  
   RunSuccessor;  
end.