Determine if only one instance is running: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Phix}}: IupCloseOnEscape no longer needed)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(5 intermediate revisions by 5 users not shown)
Line 4:
 
=={{header|Ada}}==
 
The following solution tries to open a file for reading. If the file does ''not'' exist, a 'Name_Error' is raised. The exception handler creates that file, allows the program to perform its task, and, eventually, makes sure the file is deleted. If no exception is raised, the file exists, so another instance is running, and the program stops. It also stops if the wrong exception is raised, i.e., any exception other than 'Name_Error'.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Single_Instance is
Line 34 ⟶ 33:
exception
when others => IO.Delete(Lock_File);
end Single_Instance;</langsyntaxhighlight>
 
Note that there is a race condition: If another instance tries to open the file for reading, before the first one has created it, then more than one instance will actually run.
Line 41 ⟶ 40:
AutoHotkey has a #SingleInstance command. If you run two scripts that don't have it at the same time, it alerts the user. #SingleInstance FORCE closes the older instance when a newer one is run, and #SingleInstance IGNORE does nothing when you try to open a new instance of an already-running script.
 
=={{header|BaConBASIC}}==
==={{header|BaCon}}===
Using advisory locks from libc.
<langsyntaxhighlight lang="bacon">PRAGMA INCLUDE <sys/file.h>
OPTION DEVICE O_NONBLOCK
 
Line 56:
SLEEP 5000
 
CLOSE DEVICE me</langsyntaxhighlight>
 
=={{header|Bash Shell}}==
Line 62:
Using flock, exits 0 if you got the lock, otherwise exits 1, below is a simplified example:
 
<langsyntaxhighlight lang="bbcbasic">
local fd=${2:-200}
 
Line 72:
&& # do something if you got the lock \
|| # do something if you did not get the lock
</syntaxhighlight>
</lang>
 
There's a nice program called singleton that wraps this in an easy to use package : https://github.com/krezreb/singleton
Line 79:
{{works with|BBC BASIC for Windows}}
Change 'UniqueLockName' to something more likely to be unique, such as a GUID.
<langsyntaxhighlight lang="bbcbasic"> SYS "CreateMutex", 0, 1, "UniqueLockName" TO Mutex%
SYS "GetLastError" TO lerr%
IF lerr% = 183 THEN
Line 89:
SYS "ReleaseMutex", Mutex%
SYS "CloseHandle", Mutex%
END</langsyntaxhighlight>
 
=={{header|C}}==
Line 100:
 
{{libheader|POSIX}}
<langsyntaxhighlight lang="c">#include <fcntl.h> /* fcntl, open */
#include <stdlib.h> /* atexit, getenv, malloc */
#include <stdio.h> /* fputs, printf, puts, snprintf */
Line 193:
puts("Fin!");
return 0;
}</langsyntaxhighlight>
 
=== POSIX with file creation ===
Line 203:
 
{{libheader|POSIX}}
<langsyntaxhighlight lang="c">#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
Line 238:
unlink("/tmp/MyUniqueName"); close(myfd);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
===Using a TCP Port===
 
<langsyntaxhighlight lang="csharp">using System;
using System.Net;
using System.Net.Sockets;
Line 260:
}
}
}</langsyntaxhighlight>
 
===Using a mutex===
<langsyntaxhighlight lang="csharp">
// Use this class in your process to guard against multiple instances
//
Line 341:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 347:
{{works with|Windows|2000 or later}}
This line needs to be near the top of the file (or in stdafx.h, if you use one.)
<syntaxhighlight lang ="cpp">#include <afx.h></langsyntaxhighlight>
 
You need a variable of type HANDLE with the same lifetime as your program. Perhaps as a member of your CWinApp object.
<syntaxhighlight lang ="cpp">HANDLE mutex;</langsyntaxhighlight>
 
At the earliest possible point in your program, you need to initialize it and perform your check. "MyApp" should be a string unique to your application. See [http://msdn2.microsoft.com/en-us/library/ms682411.aspx here] for full details.
 
<langsyntaxhighlight lang="cpp">mutex = CreateMutex( NULL, TRUE, "MyApp" );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
{
// There's another instance running. What do you do?
}</langsyntaxhighlight>
 
Finally, near the end of your program, you need to close the mutex.
<syntaxhighlight lang ="cpp">CloseHandle( mutex );</langsyntaxhighlight>
 
=={{header|Clojure}}==
{{trans|Java}}
<langsyntaxhighlight lang="clojure">(import (java.net ServerSocket InetAddress))
 
(def *port* 12345) ; random large port number
(try (new ServerSocket *port* 10 (. InetAddress getLocalHost))
(catch IOException e (System/exit 0))) ; port taken, so app is already running </langsyntaxhighlight>
 
=={{header|D}}==
Line 380:
All we need is to generate a unique name for our program and pass it as the address when calling bind(). The trick is that instead of specifying a file path as the address, we pass a null byte followed by the name of our choosing (e.g. "\0my-unique-name"). The initial null byte is what distinguishes abstract socket names from conventional Unix domain socket path names, which consist of a string of one or more non-null bytes terminated by a null byte.
Read more here: [https://blog.petrzemek.net/2017/07/24/ensuring-that-a-linux-program-is-running-at-most-once-by-using-abstract-sockets/]
<syntaxhighlight lang="d">
<lang d>
bool is_unique_instance()
{
Line 401:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program OneInstance;
 
{$APPTYPE CONSOLE}
Line 430:
end;
end;
end.</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 443:
called as register(aname,<0.42.0>)
</pre>
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Shell("tasklist > temp.txt")
 
Dim linea As String
Open "temp.txt" For Input As #1
Do While Not Eof(1)
Line Input #1, linea
If Instr(linea, "fbc.exe") = 0 Then Print "Task is Running" : Exit Do
Loop
Close #1
Shell("del temp.txt")
Sleep</syntaxhighlight>
 
 
=={{header|Go}}==
Line 448 ⟶ 463:
Recommended over file based solutions. It has the advantage that the port is always released
when the process ends.
<langsyntaxhighlight lang="go">package main
 
import (
Line 466 ⟶ 481:
fmt.Println("single instance started")
time.Sleep(10 * time.Second)
}</langsyntaxhighlight>
===File===
Solution using O_CREATE|O_EXCL. This solution has the problem that if anything terminates the
program early, the lock file remains.
<langsyntaxhighlight lang="go">package main
 
import (
Line 493 ⟶ 508:
time.Sleep(10 * time.Second)
os.Remove(lfn)
}</langsyntaxhighlight>
Here's a fluffier version that stores the PID in the lock file to provide better messages.
It has the same problem of the lock file remaining if anything terminates the program early.
<langsyntaxhighlight lang="go">package main
 
import (
Line 544 ⟶ 559:
fmt.Println(os.Getpid(), "running...")
time.Sleep(1e10)
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Simple implementation using a lock file. Two threads are launched, but the second cannot start because the first has created a lock file which is deleted when it has finished.
<langsyntaxhighlight Haskelllang="haskell">import Control.Concurrent
import System.Directory (doesFileExist, getAppUserDataDirectory,
removeFile)
Line 589 ⟶ 604:
-- thus will exit immediately
forkIO oneInstance
return ()</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 595 ⟶ 610:
The following only works in Unicon. The program uses a socket as a flag.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
if not open(":"||54321,"na") then stop("Already running")
repeat {} # busy loop
end</langsyntaxhighlight>
 
Sample run:
Line 611 ⟶ 626:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
Line 645 ⟶ 660:
}
}
}</langsyntaxhighlight>
 
=={{header|Jsish}}==
Using a socket on a fixed port number.
<langsyntaxhighlight lang="javascript">/* Determine if only one instance, in Jsish */
var sock;
 
Line 660 ⟶ 675:
puts('Applicaion already running');
exit(1);
}</langsyntaxhighlight>
 
{{out}}
Line 678 ⟶ 693:
 
=={{header|Julia}}==
{{trans|Java}}<langsyntaxhighlight lang="julia">
using Sockets
 
Line 696 ⟶ 711:
 
canopen()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.io.IOException
Line 734 ⟶ 749:
SingleInstance.close()
}
}</langsyntaxhighlight>
 
{{out}}
Line 749 ⟶ 764:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
 
local(lockfile = file('/tmp/myprocess.lockfile'))
Line 770 ⟶ 785:
sleep(10000)
 
stdoutnl('Execution done')</langsyntaxhighlight>
 
Output Window 1:
Line 784 ⟶ 799:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">'Create a Mutex to prevent more than one instance from being open at a single time.
CallDLL #kernel32, "CreateMutexA", 0 as Long, 1 as Long, "Global\My Program" as ptr, mutex as ulong
CallDLL #kernel32, "GetLastError", LastError as Long
Line 799 ⟶ 814:
calldll #kernel32, "ReleaseMutex", mutex as ulong, ret as ulong
calldll #kernel32, "CloseHandle", mutex as ulong, ret as ulong
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
We can lock a file in user folder. Only one instance can lock a file.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Try {
Line 813 ⟶ 828:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
$Epilog is the action performed upon session exit.
Running the following code before any other code will prevent 2 instances from concurrent execution.
<langsyntaxhighlight Mathematicalang="mathematica">$Epilog := Print["Another instance is running "];
If[Attributes[Global`Mutex] == {Protected},
Exit[],
Global`Mutex[x_] := Locked; Protect[Global`Mutex];
]</langsyntaxhighlight>
 
=={{header|Nim}}==
===fcntl based===
 
<langsyntaxhighlight lang="nim">import os, posix
 
let fn = getHomeDir() & "rosetta-code-lock"
Line 845 ⟶ 860:
echo i
sleep 1000
echo "Fin!"</langsyntaxhighlight>
 
===Unix Domain Socket based===
 
<langsyntaxhighlight lang="nim">import options, os
from net import newSocket, bindUnix
from nativesockets import AF_UNIX, SOCK_DGRAM, IPPROTO_IP
Line 883 ⟶ 898:
server()
else:
client()</langsyntaxhighlight>
 
=={{header|OCaml}}==
Replicates the '''C''' example, with the library [http://ocaml-sem.sourceforge.net/ ocaml-sem].
<langsyntaxhighlight lang="ocaml">open Sem
 
let () =
Line 897 ⟶ 912:
(* end of the app *)
sem_unlink "MyUniqueName";
sem_close sem</langsyntaxhighlight>
 
The standard library of OCaml also provides a [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Mutex.html Mutex] module.
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">functor
import Application Open System
define
Line 923 ⟶ 938:
{{New Open.file init(name:stdin)} read(list:_ size:1)}
{Application.exit 0}
end</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 929 ⟶ 944:
 
Then it tries to get a lock to its own file, from where the script was called.
<langsyntaxhighlight lang="perl">use Fcntl ':flock';
 
INIT
Line 937 ⟶ 952:
}
 
sleep 60; # then your code goes here</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>-- demo\rosetta\Single_instance.exw
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Single_instance.exw</span>
include pGUI.e
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
 
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
function copydata_cb(Ihandle /*ih*/, atom pCommandLine, integer size)
-- (the first instance is sent a copy of the second one's command line)
<span style="color: #008080;">function</span> <span style="color: #000000;">copydata_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">pCommandLine</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">size</span><span style="color: #0000FF;">)</span>
printf(1,"COPYDATA(%s, %d)\n",{peek_string(pCommandLine), size});
<span style="color: #000080;font-style:italic;">-- (the first instance is sent a copy of the second one's command line)</span>
return IUP_DEFAULT;
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"COPYDATA(%s, %d)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">peek_string</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pCommandLine</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">size</span><span style="color: #0000FF;">});</span>
end function
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span><span style="color: #0000FF;">;</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
IupOpen()
IupSetGlobal("SINGLEINSTANCE", "Single") -- (must [partially] match the main window title)
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
if IupGetGlobal("SINGLEINSTANCE")!="" then
<span style="color: #7060A8;">IupSetGlobal</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"SINGLEINSTANCE"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Single"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (must [partially] match the main window title)</span>
Ihandle dlg = IupDialog(IupVbox({IupLabel("hello")},"MARGIN=200x200"))
<span style="color: #008080;">if</span> <span style="color: #7060A8;">IupGetGlobal</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"SINGLEINSTANCE"</span><span style="color: #0000FF;">)!=</span><span style="color: #008000;">""</span> <span style="color: #008080;">then</span>
IupSetAttribute(dlg,"TITLE","Single Instance")
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"hello"</span><span style="color: #0000FF;">)},</span><span style="color: #008000;">"MARGIN=200x200"</span><span style="color: #0000FF;">))</span>
IupSetCallback(dlg, "COPYDATA_CB", Icallback("copydata_cb"));
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Single Instance"</span><span style="color: #0000FF;">)</span>
IupShow(dlg)
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"COPYDATA_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"copydata_cb"</span><span style="color: #0000FF;">));</span>
IupMainLoop()
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
IupClose()</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
Line 974 ⟶ 992:
<pre>$ ./myScript & # Start in the background
[1] 26438</pre>
<langsyntaxhighlight PicoLisplang="picolisp">$ pil +
: (call "killall" "-0" "-q" "myScript")
-> T</langsyntaxhighlight>
 
===Using a mutex===
Another possibility is to 'acquire' a mutex on program start, and never release
it.
<langsyntaxhighlight PicoLisplang="picolisp">: (acquire "running1")
-> 30817 # A successful call returns the PID</langsyntaxhighlight>
A second application trying to acquire the same mutex would receive 'NIL'
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
if (Get-Process -Name "notepad" -ErrorAction SilentlyContinue)
{
Line 995 ⟶ 1,013:
Start-Process -FilePath C:\Windows\notepad.exe
}
</syntaxhighlight>
</lang>
No output because notepad.exe was not running, so it was started.
{{Out}}
Line 1,001 ⟶ 1,019:
</pre>
Run it again.
<syntaxhighlight lang="powershell">
<lang PowerShell>
if (Get-Process -Name "notepad" -ErrorAction SilentlyContinue)
{
Line 1,010 ⟶ 1,028:
Start-Process -FilePath C:\Windows\notepad.exe
}
</syntaxhighlight>
</lang>
Since it is running a warning message is output.
{{Out}}
Line 1,018 ⟶ 1,036:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#MyApp="MyLittleApp"
Mutex=CreateMutex_(0,1,#MyApp)
If GetLastError_()=#ERROR_ALREADY_EXISTS
Line 1,028 ⟶ 1,046:
 
ReleaseMutex_(Mutex)
End</langsyntaxhighlight>
 
=={{header|Python}}==
Line 1,036 ⟶ 1,054:
Must be run from an application, not the interpreter.
 
<langsyntaxhighlight lang="python">import __main__, os
 
def isOnlyInstance():
Line 1,043 ⟶ 1,061:
return os.system("(( $(ps -ef | grep python | grep '[" +
__main__.__file__[0] + "]" + __main__.__file__[1:] +
"' | wc -l) > 1 ))") != 0</langsyntaxhighlight>
 
This is not a solution - one can run the same app by copying the code to another location. A solution may be a lock file or lock directory created by the first instance and hold while the first instance is running.
Line 1,049 ⟶ 1,067:
=={{header|Racket}}==
{{trans|Java}}
<langsyntaxhighlight lang="racket">
#lang racket
(define *port* 12345) ; random large port number
Line 1,057 ⟶ 1,075:
(printf "Working...\n")
(sleep 10)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,063 ⟶ 1,081:
{{works with|rakudo|2018.03}}
An old-school Unix solution, none the worse for the wear:
<syntaxhighlight lang="raku" perl6line>my $name = $*PROGRAM-NAME;
my $pid = $*PID;
 
Line 1,093 ⟶ 1,111:
}
note "Got lock!";
unlink $lockpid;</langsyntaxhighlight>
 
=={{header|REXX}}==
{{works with|ARexx}}
Solutions using a temporary file as a semaphore aren't very clean; if the program ends abruptly, the file isn't cleaned up. In this solution, we will instead open an ARexx port of our own. Ports are automatically closed by the interpreter if the program is ABENDed.
<langsyntaxhighlight lang="rexx">/* Simple ARexx program to open a port after checking if it's already open */
IF Show('PORTS','ROSETTA') THEN DO /* Port is already open; exit */
SAY 'This program may only be run in a single instance at a time.'
Line 1,115 ⟶ 1,133:
END
 
EXIT 0</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Determine if only one instance is running
 
Line 1,141 ⟶ 1,159:
end
return sum
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,149 ⟶ 1,167:
=={{header|Ruby}}==
Uses file locking on the program file
<langsyntaxhighlight lang="ruby">def main
puts "first instance"
sleep 20
Line 1,163 ⟶ 1,181:
end
 
__END__</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">if instr(shell$("tasklist"),"rbp.exe") <> 0 then print "Task is Running"</langsyntaxhighlight>
 
=={{header|Rust}}==
Using TCP socket
<langsyntaxhighlight lang="rust">use std::net::TcpListener;
 
fn create_app_lock(port: u16) -> TcpListener {
Line 1,193 ⟶ 1,211:
// ...
remove_app_lock(lock_socket);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
===Java Interoperability===
{{Out}}Best seen running in your browser [https://scastie.scala-lang.org/ja0sMzt5SGKHSu3w8qnlQQ Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">import java.io.IOException
import java.net.{InetAddress, ServerSocket}
 
Line 1,220 ⟶ 1,238:
sys.exit(0)
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby"># For this to work, you need to explicitly
# store the returned fh inside a variable.
var fh = File(__FILE__).open_r
Line 1,234 ⟶ 1,252:
say "Running..."
Sys.sleep(20)
say 'Done!'</langsyntaxhighlight>
 
=={{header|Swift}}==
Uses NSDistributedNotificationCenter. Works with Swift 1.2.
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
let globalCenter = NSDistributedNotificationCenter.defaultCenter()
Line 1,263 ⟶ 1,281:
 
send()
CFRunLoopRun()</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{trans|Java}}
{{works with|Tcl|8.6}}
<langsyntaxhighlight Tcllang="tcl">package require Tcl 8.6
try {
# Pick a port number based on the name of the main script executing
Line 1,277 ⟶ 1,295:
puts stderr "Application $::argv0 already running?"
exit 1
}</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 1,283 ⟶ 1,301:
==== Microsoft Windows ====
 
<langsyntaxhighlight lang="txrlisp">;;; Define some typedefs for clear correspondence with Win32
(typedef HANDLE cptr)
(typedef LPSECURITY_ATTRIBUTES cptr)
Line 1,307 ⟶ 1,325:
)
(CloseHandle m)</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 1,313 ⟶ 1,331:
{{works with|Bourne Shell}}
{{works with|Bourne Again SHell}}
<syntaxhighlight lang="sh">
<lang sh>
# (c) Copyright 2005 Mark Hobley
#
Line 1,350 ⟶ 1,368:
fi
}
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic}}==
Line 1,356 ⟶ 1,374:
{{works with|Visual Basic|5}}
{{works with|Visual Basic|6}}
<langsyntaxhighlight lang="vb">Dim onlyInstance as Boolean
onlyInstance = not App.PrevInstance</langsyntaxhighlight>
 
=={{header|Wren}}==
This works by trying to create a special file with exclusive access.
 
If this fails then the error is captured, a suitable message is printed and the script exits.
 
Otherwise, the script completes normally and the special file is deleted just before it exits.
<syntaxhighlight lang="wren">import "io" for File, FileFlags
 
var specialFile = "wren-exclusive._sp"
var checkOneInstanceRunning = Fn.new {
// attempt to create the special file with exclusive access
var ff = FileFlags.create | FileFlags.exclusive
File.openWithFlags(specialFile, ff) { |file| } // closes automatically if successful
}
 
// check if the current instance is the only one running
var fiber = Fiber.new {
checkOneInstanceRunning.call()
}
var error = fiber.try()
if (error) {
System.print("An instance is already running.")
return
}
 
// do something that takes a while for testing purposes
var sum = 0
for (i in 1...1e8) {
sum = sum + i
}
System.print(sum)
 
File.delete(specialFile) // clean up</syntaxhighlight>
 
{{out}}
<pre>
(in window 1)
$ wren one_instance_running.wren
4.99999995e+15
$
 
(in window2, started before the first instance completes)
$ wren one_instance_running.wren
An instance is already running.
$
</pre>
 
{{omit from|ACL2}}
9,476

edits