<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>GSaraiva&#039;s Projects &#187; CreateMutex</title>
	<atom:link href="http://projects.pro.br/gsaraiva/tag/createmutex/feed/" rel="self" type="application/rss+xml" />
	<link>http://projects.pro.br/gsaraiva</link>
	<description>Step by step</description>
	<lastBuildDate>Tue, 01 Sep 2009 13:14:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Delphi: Utils :: AppSingleton</title>
		<link>http://projects.pro.br/gsaraiva/2008/07/delphi-utils-appsingleton/</link>
		<comments>http://projects.pro.br/gsaraiva/2008/07/delphi-utils-appsingleton/#comments</comments>
		<pubDate>Thu, 03 Jul 2008 23:02:10 +0000</pubDate>
		<dc:creator>Gilberto Saraiva</dc:creator>
				<category><![CDATA[articles]]></category>
		<category><![CDATA[AppSingleton]]></category>
		<category><![CDATA[CreateMutex]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Usefull Function]]></category>

		<guid isPermaLink="false">http://gsaraiva.projects.pro.br/?p=135</guid>
		<description><![CDATA[Folks,
This code below implement a singleton structure for the aplication, and that need to be implemented on the DPR file of the project:
uses Windows;&#160;function AppSingleton&#40;ACheckPath: boolean = false&#41;: boolean;var&#160;&#160;s: string;&#160;&#160;i, iLast: Cardinal;begin&#160;&#160;s := ParamStr&#40;0&#41;;&#160;&#160;iLast := 1;&#160;&#160;case Integer&#40;ACheckPath&#41; of&#160;&#160;&#160;&#160;0: for i := 1 to Length&#40;s&#41; do if s&#91;i&#93; = '\' then iLast := i;&#160;&#160;&#160;&#160;1: for i [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Folks,</strong></p>
<p>This code below implement a singleton structure for the aplication, and that need to be implemented on the DPR file of the project:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title="Delphi"><div class="devcodeoverflow"><ol><li><span style="color: #000000; font-weight: bold;">uses</span> Windows<span style="color: #000066;">;</span></li><li>&nbsp;</li><li><span style="color: #000000; font-weight: bold;">function</span> AppSingleton<span style="color: #000066;">&#40;</span>ACheckPath<span style="color: #000066;">:</span> <span style="color: #000066; font-weight: bold;">boolean</span> <span style="color: #000066;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #000066;">&#41;</span><span style="color: #000066;">:</span> <span style="color: #000066; font-weight: bold;">boolean</span><span style="color: #000066;">;</span></li><li><span style="color: #000000; font-weight: bold;">var</span></li><li>&nbsp;&nbsp;s<span style="color: #000066;">:</span> <span style="color: #000066; font-weight: bold;">string</span><span style="color: #000066;">;</span></li><li>&nbsp;&nbsp;i<span style="color: #000066;">,</span> iLast<span style="color: #000066;">:</span> <span style="color: #000066; font-weight: bold;">Cardinal</span><span style="color: #000066;">;</span></li><li><span style="color: #000000; font-weight: bold;">begin</span></li><li>&nbsp;&nbsp;s <span style="color: #000066;">:</span><span style="color: #000066;">=</span> <span style="color: #000066;">ParamStr</span><span style="color: #000066;">&#40;</span>0<span style="color: #000066;">&#41;</span><span style="color: #000066;">;</span></li><li>&nbsp;&nbsp;iLast <span style="color: #000066;">:</span><span style="color: #000066;">=</span> <span style="color: #0000ff;">1</span><span style="color: #000066;">;</span></li><li>&nbsp;&nbsp;<span style="color: #000000; font-weight: bold;">case</span> <span style="color: #000066; font-weight: bold;">Integer</span><span style="color: #000066;">&#40;</span>ACheckPath<span style="color: #000066;">&#41;</span> <span style="color: #000000; font-weight: bold;">of</span></li><li>&nbsp;&nbsp;&nbsp;&nbsp;0<span style="color: #000066;">:</span> <span style="color: #000000; font-weight: bold;">for</span> i <span style="color: #000066;">:</span><span style="color: #000066;">=</span> 1 <span style="color: #000000; font-weight: bold;">to</span> <span style="color: #000066;">Length</span><span style="color: #000066;">&#40;</span>s<span style="color: #000066;">&#41;</span> <span style="color: #000000; font-weight: bold;">do</span> <span style="color: #000000; font-weight: bold;">if</span> s<span style="color: #000066;">&#91;</span>i<span style="color: #000066;">&#93;</span> <span style="color: #000066;">=</span> <span style="color: #ff0000;">'\'</span> <span style="color: #000000; font-weight: bold;">then</span> iLast <span style="color: #000066;">:</span><span style="color: #000066;">=</span> i<span style="color: #000066;">;</span></li><li>&nbsp;&nbsp;&nbsp;&nbsp;1<span style="color: #000066;">:</span> <span style="color: #000000; font-weight: bold;">for</span> i <span style="color: #000066;">:</span><span style="color: #000066;">=</span> 1 <span style="color: #000000; font-weight: bold;">to</span> <span style="color: #000066;">Length</span><span style="color: #000066;">&#40;</span>s<span style="color: #000066;">&#41;</span> <span style="color: #000000; font-weight: bold;">do</span> <span style="color: #000000; font-weight: bold;">if</span> s<span style="color: #000066;">&#91;</span>i<span style="color: #000066;">&#93;</span> <span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000066;">&#91;</span><span style="color: #ff0000;">':'</span><span style="color: #000066;">,</span><span style="color: #ff0000;">'\'</span><span style="color: #000066;">,</span><span style="color: #ff0000;">'.'</span><span style="color: #000066;">,</span><span style="color: #ff0000;">' '</span><span style="color: #000066;">&#93;</span> <span style="color: #000000; font-weight: bold;">then</span> s<span style="color: #000066;">&#91;</span>i<span style="color: #000066;">&#93;</span> <span style="color: #000066;">:</span><span style="color: #000066;">=</span> <span style="color: #ff0000;">'_'</span><span style="color: #000066;">;</span></li><li>&nbsp;&nbsp;<span style="color: #000000; font-weight: bold;">end</span><span style="color: #000066;">;</span></li><li>&nbsp;&nbsp;Result <span style="color: #000066;">:</span><span style="color: #000066;">=</span> <span style="color: #000066;">&#40;</span>CreateMutex<span style="color: #000066;">&#40;</span><span style="color: #000000; font-weight: bold;">nil</span><span style="color: #000066;">,</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #000066;">,</span> <span style="color: #000066; font-weight: bold;">PChar</span><span style="color: #000066;">&#40;</span><span style="color: #000066; font-weight: bold;">Cardinal</span><span style="color: #000066;">&#40;</span><span style="color: #000066;">@</span>s<span style="color: #000066;">&#41;</span> <span style="color: #000066;">+</span> <span style="color: #000066;">&#40;</span>iLast <span style="color: #000066;">-</span> 1<span style="color: #000066;">&#41;</span><span style="color: #000066;">&#41;</span><span style="color: #000066;">&#41;</span> &lt;&gt; 0<span style="color: #000066;">&#41;</span> <span style="color: #000000; font-weight: bold;">and</span></li><li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #000066;">&#40;</span><span style="color: #000066;">GetLastError</span> <span style="color: #000066;">=</span> 0<span style="color: #000066;">&#41;</span><span style="color: #000066;">;</span></li><li><span style="color: #000000; font-weight: bold;">end</span><span style="color: #000066;">;</span></li></ol></div></pre><!--END_DEVFMTCODE--></p>
<p>I use the <a href="http://gsaraiva.projects.pro.br/?p=30"><strong>CreateMutex</strong></a> API that works as a semaphore, if open, the application is unique, if closed the application is already running.</p>
<p>I wrote a condition to check the full path of the application for the Mutex call, so if you want to check the full path use the funciotn with param as True, the default is False and the check will be only on the application exe name.</p>
<p>A little detail about checking the functionality of this function:<br />
Under debug mode the checkout on full path mode will fail and more then one application can be raised. This problem is because the relationship of the application with other program, so the CreateMutex API understand the Process ID is diferent from others.</p>
]]></content:encoded>
			<wfw:commentRss>http://projects.pro.br/gsaraiva/2008/07/delphi-utils-appsingleton/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Delphi: CreateMutex</title>
		<link>http://projects.pro.br/gsaraiva/2008/05/delphi-createmutex/</link>
		<comments>http://projects.pro.br/gsaraiva/2008/05/delphi-createmutex/#comments</comments>
		<pubDate>Tue, 20 May 2008 01:54:39 +0000</pubDate>
		<dc:creator>Gilberto Saraiva</dc:creator>
				<category><![CDATA[articles]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[CloseHandle]]></category>
		<category><![CDATA[CreateMutex]]></category>
		<category><![CDATA[Kernel32]]></category>
		<category><![CDATA[Mutex]]></category>
		<category><![CDATA[Mutex Object]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://gsaraiva.projects.pro.br/?p=30</guid>
		<description><![CDATA[Camaradas,
O CreateMutex é uma função disponibilizada pela plataforma Windows ( API ) que cria uma sinalização a nível de processo na Kernel32, ou seja, você poderá criar uma sinalização mutex que lhe servirá para várias finalidades e uma das principais é impedir que o mesmo aplicativo seja executado duas vezes.
function CreateMutex&#40;lpMutexAttributes: PSecurityAttributes; bInitialOwner: BOOL; lpName: [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Camaradas,</strong></p>
<p>O CreateMutex é uma função disponibilizada pela plataforma Windows ( API ) que cria uma sinalização a nível de processo na Kernel32, ou seja, você poderá criar uma sinalização mutex que lhe servirá para várias finalidades e uma das principais é impedir que o mesmo aplicativo seja executado duas vezes.</p>
<p><!--DEVFMTCODE--><pre class="devcodeblock" title="Delphi"><div class="devcodeoverflow"><ol><li><span style="color: #000000; font-weight: bold;">function</span> CreateMutex<span style="color: #000066;">&#40;</span>lpMutexAttributes<span style="color: #000066;">:</span> PSecurityAttributes<span style="color: #000066;">;</span> bInitialOwner<span style="color: #000066;">:</span> <span style="color: #000066; font-weight: bold;">BOOL</span><span style="color: #000066;">;</span> lpName<span style="color: #000066;">:</span> <span style="color: #000066; font-weight: bold;">PChar</span><span style="color: #000066;">&#41;</span><span style="color: #000066;">:</span> <span style="color: #000066; font-weight: bold;">THandle</span><span style="color: #000066;">;</span> <span style="color: #000000; font-weight: bold;">stdcall</span><span style="color: #000066;">;</span></li><li><span style="color: #008000; font-style: italic;">{$EXTERNALSYM CreateMutex}</span></li></ol></div></pre><!--END_DEVFMTCODE--></p>
<p>O exemplo abaixo impede a execução do mesmo aplicativo por mais de uma vez no mesmo computador:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title="Delphi"><div class="devcodeoverflow"><ol><li><span style="color: #000000; font-weight: bold;">program</span> Project1<span style="color: #000066;">;</span></li><li>&nbsp;</li><li><span style="color: #000000; font-weight: bold;">uses</span></li><li>&nbsp;&nbsp;Forms<span style="color: #000066;">,</span></li><li>&nbsp;&nbsp;Windows<span style="color: #000066;">,</span></li><li>&nbsp;&nbsp;Dialogs<span style="color: #000066;">,</span></li><li>&nbsp;&nbsp;Unit1 <span style="color: #000000; font-weight: bold;">in</span> <span style="color: #ff0000;">'Unit1.pas'</span> <span style="color: #808080; font-style: italic;">{Form1}</span><span style="color: #000066;">;</span></li><li>&nbsp;</li><li><span style="color: #008000; font-style: italic;">{$R *.res}</span></li><li>&nbsp;</li><li><span style="color: #000000; font-weight: bold;">var</span></li><li>&nbsp;&nbsp;hMutex<span style="color: #000066;">:</span> <span style="color: #000066; font-weight: bold;">THandle</span><span style="color: #000066;">;</span></li><li><span style="color: #000000; font-weight: bold;">begin</span></li><li>&nbsp;&nbsp;hMutex <span style="color: #000066;">:</span><span style="color: #000066;">=</span> CreateMutex<span style="color: #000066;">&#40;</span><span style="color: #000000; font-weight: bold;">nil</span><span style="color: #000066;">,</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #000066;">,</span> <span style="color: #000066; font-weight: bold;">PChar</span><span style="color: #000066;">&#40;</span><span style="color: #ff0000;">'MeuNomeUnico'</span><span style="color: #000066;">&#41;</span><span style="color: #000066;">&#41;</span><span style="color: #000066;">;</span></li><li>&nbsp;&nbsp;<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #000066;">&#40;</span>hMutex &lt;&gt; 0<span style="color: #000066;">&#41;</span> <span style="color: #000000; font-weight: bold;">and</span> <span style="color: #000066;">&#40;</span><span style="color: #000066;">GetLastError</span> <span style="color: #000066;">=</span> 0<span style="color: #000066;">&#41;</span> <span style="color: #000000; font-weight: bold;">then</span></li><li>&nbsp;&nbsp;<span style="color: #000000; font-weight: bold;">begin</span></li><li>&nbsp;&nbsp;&nbsp;&nbsp;Application<span style="color: #000066;">.</span><span style="color: #000066;">Initialize</span><span style="color: #000066;">;</span></li><li>&nbsp;&nbsp;&nbsp;&nbsp;Application<span style="color: #000066;">.</span><span style="color: #006600;">CreateForm</span><span style="color: #000066;">&#40;</span>TForm1<span style="color: #000066;">,</span> Form1<span style="color: #000066;">&#41;</span><span style="color: #000066;">;</span></li><li>&nbsp;&nbsp;&nbsp;&nbsp;Application<span style="color: #000066;">.</span><span style="color: #006600;">Run</span><span style="color: #000066;">;</span></li><li>&nbsp;&nbsp;<span style="color: #000000; font-weight: bold;">end</span> <span style="color: #000000; font-weight: bold;">else</span></li><li>&nbsp;&nbsp;&nbsp;&nbsp;ShowMessage<span style="color: #000066;">&#40;</span><span style="color: #ff0000;">'Aplicativo já está rodando.'</span><span style="color: #000066;">&#41;</span><span style="color: #000066;">;</span></li><li><span style="color: #000000; font-weight: bold;">end</span><span style="color: #000066;">.</span></li><li></li></ol></div></pre><!--END_DEVFMTCODE--><br />
Utilizando basicamente, o 3º parametro do CreateMutex é aonde informamos qual o nome único utilizaremos, para que na tentativa de criação da sinalização, a Kernel32 verifique se há alguma sinalização de nome igual ( A verificação é em case-sensitive ).</p>
<p>Já que vimos a utilização básica de uma sinalização a nível de kernel podemos entender como o sistema funciona.</p>
<dl>
<li>Ao utilizar o CreateMutex, criamos uma sinalização mutex controlada e gerenciada pela Kernel32, ou seja, seu aplicativo em nada muda ao chamar esse API.</li>
<li>Como o controle de todos os processos é feito pela Kernel32, em hipótese de travamento de seu programa não há possibilidade da sinalização Mutex ficar retida, pois ao detectar que o processo foi extinto a Kernel32 retira a sinalização automaticamente.</li>
<li>Após criada uma sinalização Mutex, enquanto ela não for fechado ( Utiliza-se CloseHandle para essa finalidade ), a sinalização ficará de posse da primeira execução do aplicativo. Então quando executado pela segunda vez, ao tentar criar uma sinalização com o mesmo nome, a Kernel32 retorna um erro, aonde se é interpretado que a sinalização já existe e assim indicando que o processo já está executado.
<li>A sinalização mutex ( Mutex Object ) poderá ser utilizada de várias formas, compreende-se em sinalização de controle de acessos à algum ponto ou objeto comum a mais de um processo ( Threads ).</li>
</dl>
<p>A matéria é muito extensa, engloba Threads, Processos, Sinalização e Semaforização de acessos além da vasta acessibilidade de Eventos Kernel32, área que já implica no entendimento de Tokens Privileges. Ou seja, assunto para mais de um artigo <img src='http://projects.pro.br/gsaraiva/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  .</p>
<p>Abraço a todos</p>
]]></content:encoded>
			<wfw:commentRss>http://projects.pro.br/gsaraiva/2008/05/delphi-createmutex/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
