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.<\/p>\n
#include <sys\/file.h><\/p>\n
#include <sys\/types.h><\/p>\n
#include <sys\/stat.h><\/p>\n
#include <fcntl.h><\/p>\n
<\/p>\n
int pid_file = -1; int rc = -1;<\/p>\n
pid_file = open(“\/var\/run\/whatever.pid”, O_CREAT | O_RDWR, 0666);<\/p>\n
rc = flock(pid_file, LOCK_EX | LOCK_NB);<\/p>\n
if(rc) {<\/p>\n
if(EWOULDBLOCK == errno) \u00a0\u00a0\u00a0 {<\/p>\n
close(pid_file); \/\/ another instance is running<\/p>\n
return;<\/p>\n
}<\/p>\n
}<\/p>\n
else {<\/p>\n
\/\/ this is the first instance<\/p>\n
}<\/p><\/blockquote>\n
<\/p>\n","protected":false},"excerpt":{"rendered":"
sample code to creating single instance application in linux.<\/p>\n","protected":false},"author":29,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1321,19,1337,310],"tags":[1339,1462,1333,1340],"class_list":["post-1373","post","type-post","status-publish","format-standard","hentry","category-favorites","category-linux","category-my-article","category-programming","tag-application","tag-linux","tag-programming-2","tag-single-instance"],"_links":{"self":[{"href":"http:\/\/blog.yogindar.org\/index.php?rest_route=\/wp\/v2\/posts\/1373","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/blog.yogindar.org\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/blog.yogindar.org\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/blog.yogindar.org\/index.php?rest_route=\/wp\/v2\/users\/29"}],"replies":[{"embeddable":true,"href":"http:\/\/blog.yogindar.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1373"}],"version-history":[{"count":1,"href":"http:\/\/blog.yogindar.org\/index.php?rest_route=\/wp\/v2\/posts\/1373\/revisions"}],"predecessor-version":[{"id":1374,"href":"http:\/\/blog.yogindar.org\/index.php?rest_route=\/wp\/v2\/posts\/1373\/revisions\/1374"}],"wp:attachment":[{"href":"http:\/\/blog.yogindar.org\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1373"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/blog.yogindar.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1373"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/blog.yogindar.org\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1373"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}