What would be your suggestion in order to create a single instance application, so that only one process is allowed to run at a time? File lock, mutex or what?
-
3The C language has no concepts for this. You must specify in which environment you want to do this, since the solution is going to be specific to that environment. – unwind Mar 17 '11 at 12:51
-
Main concern is linux environment – whoi Mar 17 '11 at 12:56
15 Answers
A good way is:
#include <sys/file.h>
#include <errno.h>
int pid_file = open("/var/run/whatever.pid", O_CREAT | O_RDWR, 0666);
int rc = flock(pid_file, LOCK_EX | LOCK_NB);
if(rc) {
if(EWOULDBLOCK == errno)
; // another instance is running
}
else {
// this is the first instance
}
Note that locking allows you to ignore stale pid files (i.e. you don't have to delete them). When the application terminates for any reason the OS releases the file lock for you.
Pid files are not terribly useful because they can be stale (the file exists but the process does not). Hence, the application executable itself can be locked instead of creating and locking a pid file.
A more advanced method is to create and bind a unix domain socket using a predefined socket name. Bind succeeds for the first instance of your application. Again, the OS unbinds the socket when the application terminates for any reason. When bind()
fails another instance of the application can connect()
and use this socket to pass its command line arguments to the first instance.

- 6,843
- 3
- 48
- 66

- 131,725
- 17
- 180
- 271
-
1`flock` is nonstandard. Use `fcntl` or `lockf` locking. – R.. GitHub STOP HELPING ICE Mar 17 '11 at 13:42
-
There is no need to use flock, and you need to check the results of the open() to see if it succeeded. If it worked, you run, if it fails because the file already exists, then you know another instance is running. – psusi Sep 15 '11 at 15:11
-
12@psusi: a) if `open()` fails `flock()` fails as well, hence no need to check the result of `open()`; b) the file may exist but it may be stale, need to lock it to check if the process exists. – Maxim Egorushkin Sep 15 '11 at 15:48
-
3What if `rc` is non-zero, but `errno != EWOULDBLOCK`? Does it matter that `errno` is checked at all? – Mark Lakata Oct 20 '14 at 22:34
-
1`/var/run` seems to be the standard place to put such files. But it's owned by root so `open()` complains about permission! Where would be a good place to put it if I don't want the process to need to be run by the superuser? – Gauthier Feb 04 '15 at 08:07
-
3@Gauthier http://www.tldp.org/LDP/Linux-Filesystem-Hierarchy/html/Linux-Filesystem-Hierarchy.html#tmp: **/tmp**: _This directory contains mostly files that are required temporarily. Many programs use this to create lock files and for temporary storage of data..._ – Maxim Egorushkin Feb 04 '15 at 09:22
-
@MaximEgorushkin: that's actually what I used while waiting for your answer. Great, thanks! – Gauthier Feb 04 '15 at 11:59
-
1This fails if the main app somhow spawn child apps after the lock. The lock file will not be deleted untill all the child processes terminate – DEKKER Apr 19 '22 at 12:13
Here is a solution in C++. It uses the socket recommendation of Maxim. I like this solution better than the file based locking solution, because the file based one fails if the process crashes and does not delete the lock file. Another user will not be able to delete the file and lock it. The sockets are automatically deleted when the process exits.
Usage:
int main()
{
SingletonProcess singleton(5555); // pick a port number to use that is specific to this app
if (!singleton())
{
cerr << "process running already. See " << singleton.GetLockFileName() << endl;
return 1;
}
... rest of the app
}
Code:
#include <netinet/in.h>
class SingletonProcess
{
public:
SingletonProcess(uint16_t port0)
: socket_fd(-1)
, rc(1)
, port(port0)
{
}
~SingletonProcess()
{
if (socket_fd != -1)
{
close(socket_fd);
}
}
bool operator()()
{
if (socket_fd == -1 || rc)
{
socket_fd = -1;
rc = 1;
if ((socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
throw std::runtime_error(std::string("Could not create socket: ") + strerror(errno));
}
else
{
struct sockaddr_in name;
name.sin_family = AF_INET;
name.sin_port = htons (port);
name.sin_addr.s_addr = htonl (INADDR_ANY);
rc = bind (socket_fd, (struct sockaddr *) &name, sizeof (name));
}
}
return (socket_fd != -1 && rc == 0);
}
std::string GetLockFileName()
{
return "port " + std::to_string(port);
}
private:
int socket_fd = -1;
int rc;
uint16_t port;
};

- 19,989
- 5
- 106
- 123
-
on compiler before gcc 4.7, it gives "SingletonProcess.h:42:29: error: ISO C++ forbids in-class initialization of non-const static member ‘socket_fd’ " – sb32134 Dec 14 '16 at 12:55
-
so, i did initilizsed in the beginning of class with : SingletonProcess() : socket_fd(-1) {} – sb32134 Dec 14 '16 at 13:44
-
2Be careful. Spawned child processes inherit this file descriptor. So after the process is completed netstat shows that port 5555 is used by the child process – Alptugay Nov 27 '17 at 10:41
-
Be careful #2: I had some mysterious issues with (linux) startup scripts not starting one of these processes sporadically. I haven't proved it, but I suspect it was because I had forgotten to add `network` to `Required-Start` in the init script. Perhaps if the network is not yet initialized, the bind (or socket creation) will fail... – logidelic Nov 07 '18 at 15:11
-
Why don't you use RAII? Create and connect the socket on instantiation and close it on desctruction. (Use either a status bit (like std::fstream does) or throw on failure to handle the error) – JulianW Jun 24 '19 at 09:53
-
@JulianH You could use RAII, and that would work in most cases. By separating the ctor from the locking method, you have a chance to delay locking of the process when you want to . For example, you might want to have a `Singleton` member object, but you don't want to lock the process immediately during the construction of the parent object. – Mark Lakata Jun 25 '19 at 23:19
-
@MarkLakata for this purpose you could provide a ctr without arguments + a move ctr, basically like `std::thread`does. – JulianW Jun 27 '19 at 00:06
Avoid file-based locking
It is always good to avoid a file based locking mechanism to implement the singleton instance of an application. The user can always rename the lock file to a different name and run the application again as follows:
mv lockfile.pid lockfile1.pid
Where lockfile.pid
is the lock file based on which is checked for existence before running the application.
So, it is always preferable to use a locking scheme on object directly visible to only the kernel. So, anything which has to do with a file system is not reliable.
So the best option would be to bind to a inet socket. Note that unix domain sockets reside in the filesystem and are not reliable.
Alternatively, you can also do it using DBUS.

- 41,871
- 30
- 130
- 181

- 59
- 1
- 1
-
5On the other hand, with an inet socket, a user could open that socket before the application, to prevent it from being able to run (a DOS-type attack). So that's not fool-proof either. File-based locking can be made secure with [suitable permissions set up on a filesystem](http://serverfault.com/q/159334/10513). But inet sockets don't have permissions to control who can open them. – Craig McQueen May 29 '15 at 04:53
-
One can bypass the "inet socket" based lock (intentionally or accidently) by running the two instances in different network namespaces. – plugwash Aug 02 '17 at 16:08
For windows, a named kernel object (e.g. CreateEvent, CreateMutex). For unix, a pid-file - create a file and write your process ID to it.

- 88,732
- 13
- 198
- 189
You can create an "anonymous namespace" AF_UNIX socket. This is completely Linux-specific, but has the advantage that no filesystem actually has to exist.
Read the man page for unix(7) for more info.

- 62,604
- 14
- 116
- 151
-
1The correct terminology is "**abstract** namespace" (and abstract socket addresses). – Urhixidur Jun 10 '15 at 19:20
-
It's seems to not be mentioned - it is possible to create a mutex in shared memory but it needs to be marked as shared by attributes (not tested):
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_t *mutex = shmat(SHARED_MEMORY_ID, NULL, 0);
pthread_mutex_init(mutex, &attr);
There is also shared memory semaphores (but I failed to find out how to lock one):
int sem_id = semget(SHARED_MEMORY_KEY, 1, 0);

- 7,028
- 6
- 39
- 61
-
`semop()` is used for locking and unlocking System V semaphores, which `semget()` will return. (POSIX semaphores--`man sem_overview`--are usually preferable.) – David Duncan Jun 05 '15 at 04:10
No one has mentioned it, but sem_open()
creates a real named semaphore under modern POSIX-compliant OSes. If you give a semaphore an initial value of 1, it becomes a mutex (as long as it is strictly released only if a lock was successfully obtained).
With several sem_open()
-based objects, you can create all of the common equivalent Windows named objects - named mutexes, named semaphores, and named events. Named events with "manual" set to true is a bit more difficult to emulate (it requires four semaphore objects to properly emulate CreateEvent()
, SetEvent()
, and ResetEvent()
). Anyway, I digress.
Alternatively, there is named shared memory. You can initialize a pthread mutex with the "shared process" attribute in named shared memory and then all processes can safely access that mutex object after opening a handle to the shared memory with shm_open()
/mmap()
. sem_open()
is easier if it is available for your platform (if it isn't, it should be for sanity's sake).
Regardless of the method you use, to test for a single instance of your application, use the trylock()
variant of the wait function (e.g. sem_trywait()
). If the process is the only one running, it will successfully lock the mutex. If it isn't, it will fail immediately.
Don't forget to unlock and close the mutex on application exit.

- 41,871
- 30
- 130
- 181

- 2,274
- 24
- 20
-
3Unfortunately it seems that there's no way for POSIX semaphores to be "cleaned up" if a process is killed — unlike for lock files or sockets where the OS will close files or sockets if the process is killed. See [The Problem with POSIX Semaphores](http://charette.no-ip.com:81/programming/2010-01-13_PosixSemaphores/). – Craig McQueen May 29 '15 at 02:01
-
1This is a problem with the Linux kernel itself. POSIX semaphores are implemented in user space. Windows named objects are implemented in the kernel, which allows the kernel to correctly clean up after prematurely terminated processes. Since writing this answer, I switched my sync library code to utilize direct shared memory objects (shm_open()) because I found sem_open() rather lacking: https://github.com/cubiclesoft/cross-platform-cpp – CubicleSoft Jun 09 '17 at 04:08
-
Also, many *NIXes have /dev/shm mapped into the file space, which allows regular filesystem calls to be run against those objects. That includes using 'rm' to delete any broken semaphores/shared memory objects. – CubicleSoft Jun 09 '17 at 04:23
-
How can it be reliably determined if a semaphore/shared memory object is "broken"? – Craig McQueen Jun 09 '17 at 05:18
-
1A human has to notice that the application is bailing out when they try to run it manually and it tries to acquire the mutex and fails. Since another process, which no longer exists, is holding onto it (either partially or fully), the mutex will never be released. This issue is why it's the kernel's responsibility for a correct implementation of global synchronization objects and one rare area that Windows does right. – CubicleSoft Jun 09 '17 at 13:47
It will depend on which problem you want to avoid by forcing your application to have only one instance and the scope on which you consider instances.
For a daemon — the usual way is to have a /var/run/app.pid
file.
For user application, I've had more problems with applications which prevented me to run them twice than with being able to run twice an application which shouldn't have been run so. So the answer on "why and on which scope" is very important and will probably bring answer specific on the why and the intended scope.

- 730,956
- 141
- 904
- 1,278

- 51,233
- 8
- 91
- 143
Here is a solution based on sem_open
/*
*compile with :
*gcc single.c -o single -pthread
*/
/*
* run multiple instance on 'single', and check the behavior
*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <unistd.h>
#include <errno.h>
#define SEM_NAME "/mysem_911"
int main()
{
sem_t *sem;
int rc;
sem = sem_open(SEM_NAME, O_CREAT, S_IRWXU, 1);
if(sem==SEM_FAILED){
printf("sem_open: failed errno:%d\n", errno);
}
rc=sem_trywait(sem);
if(rc == 0){
printf("Obtained lock !!!\n");
sleep(10);
//sem_post(sem);
sem_unlink(SEM_NAME);
}else{
printf("Lock not obtained\n");
}
}
One of the comments on a different answer says "I found sem_open() rather lacking". I am not sure about the specifics of what's lacking

- 11
- 1
-
2If the only process of you app crashes without calling `sem_unlink`, there's no way to launch your app, not even one instance, until `sem_unlink` is called. This is the lacking part of named semaphore on POSIX OSes like Linux and macOS as they're implemented in the user space, not kernel space. – legends2k Apr 11 '22 at 13:39
Based on the hints in maxim's answer here is my POSIX solution of a dual-role daemon (i.e. a single application that can act as daemon and as a client communicating with that daemon). This scheme has the advantage of providing an elegant solution of the problem when the instance started first should be the daemon and all following executions should just load off the work at that daemon. It is a complete example but lacks a lot of stuff a real daemon should do (e.g. using syslog
for logging and fork
to put itself into background correctly, dropping privileges etc.), but it is already quite long and is fully working as is. I have only tested this on Linux so far but IIRC it should be all POSIX-compatible.
In the example the clients can send integers passed to them as first command line argument and parsed by atoi
via the socket to the daemon which prints it to stdout
. With this kind of sockets it is also possible to transfer arrays, structs and even file descriptors (see man 7 unix
).
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCKET_NAME "/tmp/exampled"
static int socket_fd = -1;
static bool isdaemon = false;
static bool run = true;
/* returns
* -1 on errors
* 0 on successful server bindings
* 1 on successful client connects
*/
int singleton_connect(const char *name) {
int len, tmpd;
struct sockaddr_un addr = {0};
if ((tmpd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) {
printf("Could not create socket: '%s'.\n", strerror(errno));
return -1;
}
/* fill in socket address structure */
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, name);
len = offsetof(struct sockaddr_un, sun_path) + strlen(name);
int ret;
unsigned int retries = 1;
do {
/* bind the name to the descriptor */
ret = bind(tmpd, (struct sockaddr *)&addr, len);
/* if this succeeds there was no daemon before */
if (ret == 0) {
socket_fd = tmpd;
isdaemon = true;
return 0;
} else {
if (errno == EADDRINUSE) {
ret = connect(tmpd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un));
if (ret != 0) {
if (errno == ECONNREFUSED) {
printf("Could not connect to socket - assuming daemon died.\n");
unlink(name);
continue;
}
printf("Could not connect to socket: '%s'.\n", strerror(errno));
continue;
}
printf("Daemon is already running.\n");
socket_fd = tmpd;
return 1;
}
printf("Could not bind to socket: '%s'.\n", strerror(errno));
continue;
}
} while (retries-- > 0);
printf("Could neither connect to an existing daemon nor become one.\n");
close(tmpd);
return -1;
}
static void cleanup(void) {
if (socket_fd >= 0) {
if (isdaemon) {
if (unlink(SOCKET_NAME) < 0)
printf("Could not remove FIFO.\n");
} else
close(socket_fd);
}
}
static void handler(int sig) {
run = false;
}
int main(int argc, char **argv) {
switch (singleton_connect(SOCKET_NAME)) {
case 0: { /* Daemon */
struct sigaction sa;
sa.sa_handler = &handler;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGINT, &sa, NULL) != 0 || sigaction(SIGQUIT, &sa, NULL) != 0 || sigaction(SIGTERM, &sa, NULL) != 0) {
printf("Could not set up signal handlers!\n");
cleanup();
return EXIT_FAILURE;
}
struct msghdr msg = {0};
struct iovec iovec;
int client_arg;
iovec.iov_base = &client_arg;
iovec.iov_len = sizeof(client_arg);
msg.msg_iov = &iovec;
msg.msg_iovlen = 1;
while (run) {
int ret = recvmsg(socket_fd, &msg, MSG_DONTWAIT);
if (ret != sizeof(client_arg)) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
printf("Error while accessing socket: %s\n", strerror(errno));
exit(1);
}
printf("No further client_args in socket.\n");
} else {
printf("received client_arg=%d\n", client_arg);
}
/* do daemon stuff */
sleep(1);
}
printf("Dropped out of daemon loop. Shutting down.\n");
cleanup();
return EXIT_FAILURE;
}
case 1: { /* Client */
if (argc < 2) {
printf("Usage: %s <int>\n", argv[0]);
return EXIT_FAILURE;
}
struct iovec iovec;
struct msghdr msg = {0};
int client_arg = atoi(argv[1]);
iovec.iov_base = &client_arg;
iovec.iov_len = sizeof(client_arg);
msg.msg_iov = &iovec;
msg.msg_iovlen = 1;
int ret = sendmsg(socket_fd, &msg, 0);
if (ret != sizeof(client_arg)) {
if (ret < 0)
printf("Could not send device address to daemon: '%s'!\n", strerror(errno));
else
printf("Could not send device address to daemon completely!\n");
cleanup();
return EXIT_FAILURE;
}
printf("Sent client_arg (%d) to daemon.\n", client_arg);
break;
}
default:
cleanup();
return EXIT_FAILURE;
}
cleanup();
return EXIT_SUCCESS;
}
All credits go to Mark Lakata. I merely did some very minor touch up only.
main.cpp
#include "singleton.hpp"
#include <iostream>
using namespace std;
int main()
{
SingletonProcess singleton(5555); // pick a port number to use that is specific to this app
if (!singleton())
{
cerr << "process running already. See " << singleton.GetLockFileName() << endl;
return 1;
}
// ... rest of the app
}
singleton.hpp
#include <netinet/in.h>
#include <unistd.h>
#include <cerrno>
#include <string>
#include <cstring>
#include <stdexcept>
using namespace std;
class SingletonProcess
{
public:
SingletonProcess(uint16_t port0)
: socket_fd(-1)
, rc(1)
, port(port0)
{
}
~SingletonProcess()
{
if (socket_fd != -1)
{
close(socket_fd);
}
}
bool operator()()
{
if (socket_fd == -1 || rc)
{
socket_fd = -1;
rc = 1;
if ((socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
throw std::runtime_error(std::string("Could not create socket: ") + strerror(errno));
}
else
{
struct sockaddr_in name;
name.sin_family = AF_INET;
name.sin_port = htons (port);
name.sin_addr.s_addr = htonl (INADDR_ANY);
rc = bind (socket_fd, (struct sockaddr *) &name, sizeof (name));
}
}
return (socket_fd != -1 && rc == 0);
}
std::string GetLockFileName()
{
return "port " + std::to_string(port);
}
private:
int socket_fd = -1;
int rc;
uint16_t port;
};

- 360
- 5
- 8
#include <windows.h>
int main(int argc, char *argv[])
{
// ensure only one running instance
HANDLE hMutexH`enter code here`andle = CreateMutex(NULL, TRUE, L"my.mutex.name");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
return 0;
}
// rest of the program
ReleaseMutex(hMutexHandle);
CloseHandle(hMutexHandle);
return 0;
}
FROM: HERE

- 11
-
As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 28 '21 at 06:49
-
The question is also tagged for linux, but you're clearly offering a Windows solution. – mitchellJ Apr 18 '22 at 20:03
On Windows you could also create a shared data segment and use an interlocked function to test for the first occurence, e.g.
#include <Windows.h>
#include <stdio.h>
#include <conio.h>
#pragma data_seg("Shared")
volatile LONG lock = 0;
#pragma data_seg()
#pragma comment(linker, "/SECTION:Shared,RWS")
void main()
{
if (InterlockedExchange(&lock, 1) == 0)
printf("first\n");
else
printf("other\n");
getch();
}

- 166
- 4
I have just written one, and tested.
#define PID_FILE "/tmp/pidfile"
static void create_pidfile(void) {
int fd = open(PID_FILE, O_RDWR | O_CREAT | O_EXCL, 0);
close(fd);
}
int main(void) {
int fd = open(PID_FILE, O_RDONLY);
if (fd > 0) {
close(fd);
return 0;
}
// make sure only one instance is running
create_pidfile();
}

- 456
- 5
- 12
-
This has a significant problem; what happens if the second process does its check after the first process's check, but before the first process creates? – M.M Jun 25 '14 at 03:51
Just run this code on a seperate thread:
void lock() {
while(1) {
ofstream closer("myapplock.locker", ios::trunc);
closer << "locked";
closer.close();
}
}
Run this as your main code:
int main() {
ifstream reader("myapplock.locker");
string s;
reader >> s;
if (s != "locked") {
//your code
}
return 0;
}

- 172
- 3
- 10
-
Buggy. Your `reader` might read nothing from the file because the file gets truncated and then written to, leaving a period of time where there's nothing in the file. – Andrew Henle Jan 07 '23 at 13:28