Determine if only one instance is running: Difference between revisions
Determine if only one instance is running (view source)
Revision as of 16:53, 24 November 2023
, 6 months ago→{{header|Wren}}: Changed to Wren S/H
m (→{{header|Wren}}: Changed to Wren S/H) |
|||
(45 intermediate revisions by 22 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'.
<
procedure Single_Instance is
Line 34 ⟶ 33:
exception
when others => IO.Delete(Lock_File);
end Single_Instance;</
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 40 ⟶ 39:
=={{header|AutoHotkey}}==
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|BASIC}}==
==={{header|BaCon}}===
Using advisory locks from libc.
<syntaxhighlight lang="bacon">PRAGMA INCLUDE <sys/file.h>
OPTION DEVICE O_NONBLOCK
OPEN ME$ FOR DEVICE AS me
IF flock(me, LOCK_EX | LOCK_NB) <> 0 THEN
PRINT "I am already running, exiting..."
END
ENDIF
PRINT "Running this program, doing things..."
SLEEP 5000
CLOSE DEVICE me</syntaxhighlight>
=={{header|Bash Shell}}==
Using flock, exits 0 if you got the lock, otherwise exits 1, below is a simplified example:
<syntaxhighlight lang="bbcbasic">
local fd=${2:-200}
# create lock file
eval "exec $fd>/tmp/my_lock.lock"
# acquire the lock, or fail
flock -nx $fd \
&& # do something if you got the lock \
|| # do something if you did not get the lock
</syntaxhighlight>
There's a nice program called singleton that wraps this in an easy to use package : https://github.com/krezreb/singleton
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
Change 'UniqueLockName' to something more likely to be unique, such as a GUID.
<
SYS "GetLastError" TO lerr%
IF lerr% = 183 THEN
Line 54 ⟶ 89:
SYS "ReleaseMutex", Mutex%
SYS "CloseHandle", Mutex%
END</
=={{header|C}}==
Line 65 ⟶ 100:
{{libheader|POSIX}}
<
#include <stdlib.h> /* atexit, getenv, malloc */
#include <stdio.h> /* fputs, printf, puts, snprintf */
Line 158 ⟶ 193:
puts("Fin!");
return 0;
}</
=== POSIX with file creation ===
Line 168 ⟶ 203:
{{libheader|POSIX}}
<
#include <signal.h>
#include <stdio.h>
Line 203 ⟶ 238:
unlink("/tmp/MyUniqueName"); close(myfd);
return 0;
}</
=={{header|C sharp|C#}}==
===Using a TCP Port===
<
using System.Net;
using System.Net.Sockets;
Line 245 ⟶ 260:
}
}
}</
===Using a mutex===
<
// Use this class in your process to guard against multiple instances
//
// This is valid for C# running on Windows, but not for C# with Linux.
//
using System;
using System.Threading;
Line 323 ⟶ 341:
}
}
}</
=={{header|C++}}==
===Microsoft Windows===
{{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></syntaxhighlight>
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;</syntaxhighlight>
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.
<syntaxhighlight lang="cpp">mutex = CreateMutex( NULL, TRUE, "MyApp" );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
{
// There's another instance running. What do you do?
}</syntaxhighlight>
Finally, near the end of your program, you need to close the mutex.
<syntaxhighlight lang="cpp">CloseHandle( mutex );</syntaxhighlight>
=={{header|Clojure}}==
{{trans|Java}}
<
(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 </
=={{header|D}}==
===Unix Domain Socket===
Unix domain sockets support another addressing mode, via the so-called abstract namespace. This allows us to bind sockets to names rather than to files. What we get are the following benefits (see page 1175 in The Linux Programming Interface):
* There is no need to worry about possible collisions with existing files in the filesystem.
* There is no socket file to be removed upon program termination.
* We do not need to create a file for the socket at all. This obviates target directory existence, permissions checks, and reduces filesystem clutter. Also, it works in chrooted environments.
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">
bool is_unique_instance()
{
import std.socket;
auto socket = new Socket(AddressFamily.UNIX, SocketType.STREAM);
auto addr = new UnixAddress("\0/tmp/myapp.uniqueness.sock");
try
{
socket.bind(addr);
return true;
}
catch (SocketOSException e)
{
import core.stdc.errno : EADDRINUSE;
if (e.errorCode == EADDRINUSE)
return false;
else
throw e;
}
}
</syntaxhighlight>
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 359 ⟶ 430:
end;
end;
end.</
=={{header|Erlang}}==
Line 372 ⟶ 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}}==
===Port===
Recommended over file based solutions. It has the advantage that the port is always released
when the process ends.
<syntaxhighlight lang="go">package main
import (
"fmt"
"net"
"time"
)
const lNet = "tcp"
const lAddr = ":12345"
func main() {
if _, err := net.Listen(lNet, lAddr); err != nil {
fmt.Println("an instance was already running")
return
}
fmt.Println("single instance started")
time.Sleep(10 * time.Second)
}</syntaxhighlight>
===File===
Solution using O_CREATE|O_EXCL. This solution has the problem that if anything terminates the
program early, the lock file remains.
<syntaxhighlight lang="go">package main
import (
"fmt"
"os"
"time"
)
// The path to the lock file should be an absolute path starting from the root.
// (If you wish to prevent the same program running in different directories,
// that is.)
const lfn = "/tmp/rclock"
func main() {
lf, err := os.OpenFile(lfn, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
if err != nil {
fmt.Println("an instance is already running")
return
}
lf.Close()
fmt.Println("single instance started")
time.Sleep(10 * time.Second)
os.Remove(lfn)
}</syntaxhighlight>
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.
<syntaxhighlight lang="go">package main
import (
Line 423 ⟶ 559:
fmt.Println(os.Getpid(), "running...")
time.Sleep(1e10)
}</
=={{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.
<
import System.Directory (doesFileExist, getAppUserDataDirectory,
removeFile)
Line 468 ⟶ 604:
-- thus will exit immediately
forkIO oneInstance
return ()</
=={{header|Icon}} and {{header|Unicon}}==
Line 474 ⟶ 610:
The following only works in Unicon. The program uses a socket as a flag.
<
if not open(":"||54321,"na") then stop("Already running")
repeat {} # busy loop
end</
Sample run:
Line 490 ⟶ 626:
=={{header|Java}}==
<
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
public class SingletonApp
{
static {
System.out.print("Application is already running,");
System.out.println(" so terminating this instance.");
System.exit(0);
}
}
public static void main(String[] args) {
System.out.print("OK, only this instance is running");
System.out.println(" but will terminate in 10 seconds.");
try {
Thread.sleep(10000);
if (s != null && !s.isClosed()) s.close();
} catch (Exception e) {
System.err.println(e);
}
}
}</syntaxhighlight>
=={{header|Jsish}}==
Using a socket on a fixed port number.
<syntaxhighlight lang="javascript">/* Determine if only one instance, in Jsish */
var sock;
try {
sock = new Socket({client:false, port:54321});
puts('\nApplication running for 30 seconds, from', strftime());
update(30000);
puts('\nApplication ended at', strftime());
} catch (err) {
puts('Applicaion already running');
exit(1);
}</syntaxhighlight>
{{out}}
<pre>prompt$ jsish oneInstance.jsi &
[1] 2003
prompt$
Application running for 30 seconds, from 2019-06-14 11:19:37
prompt$ jsish oneInstance.jsi
Applicaion already running
prompt$ jsish oneInstance.jsi
Applicaion already running
prompt$
Application ended at 2019-06-14 11:20:06
[1]+ Done jsish oneInstance.jsi</pre>
=={{header|Julia}}==
{{trans|Java}}<syntaxhighlight lang="julia">
using Sockets
const portnum = 12345
function canopen()
try
server = listen(portnum)
println("This is the only instance.")
sleep(20)
catch y
if findfirst("EADDRINUSE", string(y)) != nothing
println("There is already an instance running.")
end
end
end
canopen()
</syntaxhighlight>
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6
import java.io.IOException
import java.net.*
object SingleInstance {
private var ss: ServerSocket? = null
fun alreadyRunning(): Boolean {
try {
ss = ServerSocket(65000, 10, InetAddress.getLocalHost()) // using private port 65000
}
catch (e: IOException) {
// port already in use so an instance is already running
return true
}
return false
}
fun close() {
if (ss == null || ss?.isClosed() == true) return
ss?.close()
}
}
fun main(args: Array<String>) {
if (SingleInstance.alreadyRunning()) {
println("Application is already running, so terminating this instance")
System.exit(0)
}
else {
println("OK, only this instance is running but will terminate in 10 seconds")
Thread.sleep(10000)
SingleInstance.close()
}
}</syntaxhighlight>
{{out}}
First output window:
<pre>
OK, only this instance is running but will terminate in 10 seconds
</pre>
{{out}}
Second output window (second instance started within 10 seconds of first):
<pre>
Application is already running, so terminating this instance
</pre>
=={{header|Lasso}}==
<
local(lockfile = file('/tmp/myprocess.lockfile'))
Line 538 ⟶ 785:
sleep(10000)
stdoutnl('Execution done')</
Output Window 1:
Line 552 ⟶ 799:
=={{header|Liberty BASIC}}==
<
CallDLL #kernel32, "CreateMutexA", 0 as Long, 1 as Long, "Global\My Program" as ptr, mutex as ulong
CallDLL #kernel32, "GetLastError", LastError as Long
Line 567 ⟶ 814:
calldll #kernel32, "ReleaseMutex", mutex as ulong, ret as ulong
calldll #kernel32, "CloseHandle", mutex as ulong, ret as ulong
end</
=={{header|M2000 Interpreter}}==
We can lock a file in user folder. Only one instance can lock a file.
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Try {
Open "MYLOCK" For Output Exclusive As #F
Print "DO SOMETHING"
A$=Key$
Close#f
}
}
</syntaxhighlight>
=={{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.
<
If[Attributes[Global`Mutex] == {Protected},
Exit[],
Global`Mutex[x_] := Locked; Protect[Global`Mutex];
]</
=={{header|Nim}}==
===fcntl based===
<syntaxhighlight lang="nim">import os, posix
let fn = getHomeDir() & "rosetta-code-lock"
Line 588 ⟶ 851:
var fd = getFileHandle fn.open fmReadWrite
if fcntl(fd, F_SETLK, addr fl) < 0:
stderr.
quit 1
addQuitProc ooiUnlink
Line 597 ⟶ 860:
echo i
sleep 1000
echo "Fin!"</
===Unix Domain Socket based===
<syntaxhighlight lang="nim">import options, os
from net import newSocket, bindUnix
from nativesockets import AF_UNIX, SOCK_DGRAM, IPPROTO_IP
from posix import EADDRINUSE
const sockAddr = "\0com.myapp.sock" # Linux will delete this when the application ends
# notice the prefixed null byte, it's the Linux abstract namespace
proc server()=
echo "Unique instance detected"
proc client()=
echo "Duplicate instance detected"
when isMainModule:
var
sock = newSocket(AF_UNIX, SOCK_DGRAM, IPPROTO_IP)
isUnique: Option[bool]
try:
sock.bindUnix(sock_addr)
is_unique = some true
except OSError:
if cint(osLastError()) == EADDRINUSE:
isUnique = some false
else:
raise getCurrentException()
if unlikely is_unique.isNone:
echo "Error detecting uniqueness" # unreachable
else:
if isUnique.unsafeGet():
server()
else:
client()</syntaxhighlight>
=={{header|OCaml}}==
Replicates the '''C''' example, with the library [http://ocaml-sem.sourceforge.net/ ocaml-sem].
<
let () =
Line 611 ⟶ 912:
(* end of the app *)
sem_unlink "MyUniqueName";
sem_close sem</
The standard library of OCaml also provides a [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Mutex.html Mutex] module.
=={{header|Oz}}==
<
import Application Open System
define
Line 637 ⟶ 938:
{{New Open.file init(name:stdin)} read(list:_ size:1)}
{Application.exit 0}
end</
=={{header|Perl}}==
Line 643 ⟶ 944:
Then it tries to get a lock to its own file, from where the script was called.
<
INIT
Line 651 ⟶ 952:
}
sleep 60; # then your code goes here</
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Single_instance.exw</span>
<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>
<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>
<span style="color: #000080;font-style:italic;">-- (the first instance is sent a copy of the second one's command line)</span>
<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>
<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>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupSetGlobal</span><span style="color:
<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>
<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>
<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>
<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>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<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 725 ⟶ 992:
<pre>$ ./myScript & # Start in the background
[1] 26438</pre>
<
: (call "killall" "-0" "-q" "myScript")
-> T</
===Using a mutex===
Another possibility is to 'acquire' a mutex on program start, and never release
it.
<
-> 30817 # A successful call returns the PID</
A second application trying to acquire the same mutex would receive 'NIL'
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
if (Get-Process -Name "notepad" -ErrorAction SilentlyContinue)
{
Line 746 ⟶ 1,013:
Start-Process -FilePath C:\Windows\notepad.exe
}
</syntaxhighlight>
No output because notepad.exe was not running, so it was started.
{{Out}}
Line 752 ⟶ 1,019:
</pre>
Run it again.
<syntaxhighlight lang="powershell">
if (Get-Process -Name "notepad" -ErrorAction SilentlyContinue)
{
Line 761 ⟶ 1,028:
Start-Process -FilePath C:\Windows\notepad.exe
}
</syntaxhighlight>
Since it is running a warning message is output.
{{Out}}
Line 769 ⟶ 1,036:
=={{header|PureBasic}}==
<
Mutex=CreateMutex_(0,1,#MyApp)
If GetLastError_()=#ERROR_ALREADY_EXISTS
Line 779 ⟶ 1,046:
ReleaseMutex_(Mutex)
End</
=={{header|Python}}==
Line 787 ⟶ 1,054:
Must be run from an application, not the interpreter.
<
def isOnlyInstance():
Line 794 ⟶ 1,061:
return os.system("(( $(ps -ef | grep python | grep '[" +
__main__.__file__[0] + "]" + __main__.__file__[1:] +
"' | wc -l) > 1 ))") != 0</
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 800 ⟶ 1,067:
=={{header|Racket}}==
{{trans|Java}}
<
#lang racket
(define *port* 12345) ; random large port number
Line 808 ⟶ 1,075:
(printf "Working...\n")
(sleep 10)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2018.03}}
An old-school Unix solution, none the worse for the wear:
<syntaxhighlight lang="raku" line>my $name = $*PROGRAM-NAME;
my $pid = $*PID;
my $lockdir = "/tmp";
my $lockfile = "$lockdir/$name.pid";
my $lockpid = "$lockfile$pid";
my $havelock = False;
END {
unlink $lockfile if $havelock;
try unlink $lockpid;
}
my $pidfile = open "$lockpid", :w orelse .die;
$pidfile.say($pid);
$pidfile.close;
if try link($lockpid, $lockfile) {
$havelock = True;
}
else {
shell "kill -CONT `cat $lockfile` || rm $lockfile";
if try link($lockfile, $lockpid) {
$havelock = True;
}
else {
die "You can't run right now!";
}
}
note "Got lock!";
unlink $lockpid;</syntaxhighlight>
=={{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
<syntaxhighlight 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 831 ⟶ 1,133:
END
EXIT 0</syntaxhighlight>
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Determine if only one instance is running
task = "ringw.exe"
taskname = "tasklist.txt"
remove(taskname)
system("tasklist >> tasklist.txt")
fp = fopen(taskname,"r")
tasks = read("tasklist.txt")
counttask = count(tasks,task)
if counttask > 0
see task + " running in " + counttask + " instances" + nl
else
see task + " is not running" + nl
ok
func count(cString,dString)
sum = 0
while substr(cString,dString) > 0
sum++
cString = substr(cString,substr(cString,dString)+len(string(sum)))
end
return sum
</syntaxhighlight>
Output:
<pre>
ringw.exe running in 2 instances
</pre>
=={{header|Ruby}}==
Uses file locking on the program file
<
puts "first instance"
sleep 20
Line 851 ⟶ 1,181:
end
__END__</
=={{header|Run BASIC}}==
<
=={{header|Rust}}==
Using TCP socket
<
fn create_app_lock(port: u16) -> TcpListener {
Line 881 ⟶ 1,211:
// ...
remove_app_lock(lock_socket);
}</
=={{header|Scala}}==
===Java Interoperability===
{{Out}}Best seen running in your browser [https://scastie.scala-lang.org/ja0sMzt5SGKHSu3w8qnlQQ Scastie (remote JVM)].
<syntaxhighlight lang="scala">import java.io.IOException
import java.net.{InetAddress, ServerSocket}
object SingletonApp extends App {
private val port = 65000
try {
val s = new ServerSocket(port, 10, InetAddress.getLocalHost)
}
catch {
case _: IOException =>
// port taken, so app is already running
println("Application is already running, so terminating this instance.")
sys.exit(-1)
}
println("OK, only this instance is running but will terminate in 10 seconds.")
Thread.sleep(10000)
sys.exit(0)
}</syntaxhighlight>
=={{header|Sidef}}==
<
# store the returned fh inside a variable.
var fh = File
# Now call the flock() method on it
fh.flock(File.LOCK_EX | File.LOCK_NB) ->
|| die "I'm already running!"
# Your code here...
say "Running..."
Sys.sleep(20)
say 'Done!'
=={{header|Swift}}==
Uses NSDistributedNotificationCenter. Works with Swift 1.2.
<
let globalCenter = NSDistributedNotificationCenter.defaultCenter()
Line 924 ⟶ 1,281:
send()
CFRunLoopRun()</
=={{header|Tcl}}==
{{trans|Java}}
{{works with|Tcl|8.6}}
<
try {
# Pick a port number based on the name of the main script executing
Line 938 ⟶ 1,295:
puts stderr "Application $::argv0 already running?"
exit 1
}</
=={{header|TXR}}==
==== Microsoft Windows ====
<syntaxhighlight lang="txrlisp">;;; Define some typedefs for clear correspondence with Win32
(typedef HANDLE cptr)
(typedef LPSECURITY_ATTRIBUTES cptr)
(typedef WINERR (enum WINERR ERROR_SUCCESS
(ERROR_ALREADY_EXISTS 183)))
(typedef BOOL (enum BOOL FALSE TRUE))
(typedef LPCWSTR wstr)
;;; More familiar spelling for null pointer.
(defvarl NULL cptr-null)
;;; Define access to foreign functions.
(with-dyn-lib "kernel32.dll"
(deffi CreateMutex "CreateMutexW" HANDLE (LPSECURITY_ATTRIBUTES BOOL LPCWSTR))
(deffi CloseHandle "CloseHandle" BOOL (HANDLE))
(deffi GetLastError "GetLastError" WINERR ()))
;;; Now, the single-instance program:
(defvar m (CreateMutex NULL 'TRUE "ApplicationName"))
(unless (eq (GetLastError) 'ERROR_ALREADY_EXISTS)
;; mutual exclusion here
)
(CloseHandle m)</syntaxhighlight>
=={{header|UNIX Shell}}==
Line 944 ⟶ 1,331:
{{works with|Bourne Shell}}
{{works with|Bourne Again SHell}}
<syntaxhighlight lang="sh">
# (c) Copyright 2005 Mark Hobley
#
Line 981 ⟶ 1,368:
fi
}
</syntaxhighlight>
=={{header|Visual Basic}}==
{{works with|Visual Basic|4}} <!-- previous versions possible but unlikely; no way to test right now -->
{{works with|Visual Basic|5}}
{{works with|Visual Basic|6}}
<syntaxhighlight lang="vb">Dim onlyInstance as Boolean
onlyInstance = not App.PrevInstance</syntaxhighlight>
=={{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}}
|