Determine if only one instance is running: Difference between revisions
Content added Content deleted
(Add Jsish) |
(Add D example) |
||
Line 363: | Line 363: | ||
end; |
end; |
||
end.</lang> |
end.</lang> |
||
=={{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/] |
|||
<lang d>import std.socket; |
|||
bool is_unique_instance() { |
|||
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) { |
|||
return false; |
|||
} |
|||
} |
|||
</lang> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
From the Erlang shell, or in a program, register the application process. If this works, the process is the only one. |
From the Erlang shell, or in a program, register the application process. If this works, the process is the only one. |