blog:2019-05-30_create_a_single_instance_application_in_linux_c
2019-05-30 Create a single instance application in Linux C++
Solutions
The general approach is to write your own pid to a file in /var/run/ (/var/run/myprog.pid), When starting the program, check to see if the file exists.
This method can also be used as a communication entry when two identical programs are executed at the same time.
My program
#include <stdlib.h> /* exit, EXIT_FAILURE */
// for execution instance
#include <sys/file.h>
#include <errno.h>
...
int main (){
// ---------------------
// Check first instance,
// This can prevent multiple instance execution
int pid_file = open("./timer-test.pid", O_CREAT | O_RDWR, 0666);
int rc = flock(pid_file, LOCK_EX | LOCK_NB);
if(rc) {
if(EWOULDBLOCK == errno)
{
// another instance is running
printf ("Another Instance running\n");
exit(0);
}
}
else {
// this is the first instance
}
// ---------------------
...
-
Program normal exit:
Program break by Ctrl-C
References
Permalink blog/2019-05-30_create_a_single_instance_application_in_linux_c.txt · Last modified: 2019/05/30 09:35 by
jethro