Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a single instance application in C or C++

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?

like image 914
whoi Avatar asked Mar 17 '11 12:03

whoi


People also ask

What is a single instance application?

A Single Instance application is an application that limits the program to run only one instance at a time. This means that you cannot open the same program twice.


1 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.

like image 107
Maxim Egorushkin Avatar answered Oct 01 '22 15:10

Maxim Egorushkin