Single instance in Linux applications

Sometimes you may need to write an application in lnux for which multiple instances are not allowed. There is a simple way to achieve even though you have lot of other ways like semaphores, sockets etc to achieve the same. Here is a small snippet code to achieve the same using file locking.

#include <sys/file.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

 

int pid_file = -1; int rc = -1;

pid_file = open(“/var/run/whatever.pid”, O_CREAT | O_RDWR, 0666);

rc = flock(pid_file, LOCK_EX | LOCK_NB);

if(rc) {

if(EWOULDBLOCK == errno)     {

close(pid_file); // another instance is running

return;

}

}

else {

// this is the first instance

}

 

About the Author

Yogi

17 years of experience in various layers of software. Primarily experienced in system side software design and development on server management software. Interested in linux development in x86 and arm architecture.