I've got a situation to develop a code that can have only one instance per machine any time. And my code should be platform independent. Till this it is fine, but the problem is that I cannot have any other files except my binary. I've developed a code using fcntl, my logic is that I'll lock my binary itself, so every time the code runs it checks if it could lock and returns if it can't. This logic worked fine in ubuntu, solaris machines, but in windows I found that this logic no longer works as I can't open the running exe file. Here I attached my code where I got stuck. Please excuse me if you feel it's not the correct portal to ask, or if you feel my research is of no use. Any suggestion will be of great help to me.
#include<iostream>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<errno.h>
#define PATH "<my binary path>"
using namespace std;
int main(){
int lockfd;
FILE *FP = fopen(PATH,"wb");
if (!FP)
{
if(errno==16){
cout<<"programme is currently running hence I quit\n";// windows
}else{
cout<<"error while opening the given file\n";
cout<<"errno = "<<errno<<"\n";
}
return 1;
}else{
lockfd = fileno(FP);
}
cout<<lockfd<<"\n";
cout<<"errno = "<<errno<<"\n";
struct flock lock;
lock.l_start = 0;
lock.l_len = 0;
lock.l_type = F_WRLCK;//F_RDLCK;
lock.l_whence = SEEK_SET;
lock.l_pid = getpid();
int rc = fcntl(lockfd, F_SETLK, &lock);
cout<<"rc = "<<rc<<"\n";
cout<<"errno = "<<errno<<" eagain ="<<EAGAIN<<"\n";
if (rc == -1 && errno == EAGAIN) {
cout<<"cant lock now hence I quit\n";
return 0;
}else{
cout<<"lock done\n";
sleep(10);
//rest of the code//
}
}