0

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//
}
}
Pavani siva dath
  • 455
  • 2
  • 5
  • 12

1 Answers1

0

The simpliest edit to make would be

#ifndef WIN32
#define PATH "/export/home/dath/Desktop/singleTon.bin"
#else
#define PATH "<some path in C that you want>"
#endif

Which forces the path to be one thing for windows, and something else for all other platforms.

That said there are other cleaner ways of doing this such as shared memory which would mean that you wouldn't have to worry about leaving files around the place or hard-coding their path.

UKMonkey
  • 6,941
  • 3
  • 21
  • 30
  • 1
    The question has nothing to do with finding the path. – stark Sep 19 '17 at 10:56
  • It has everything to do with not finding the path. How do you expect to find "/export/home/dath/Desktop/singleTon.bin" on a windows box? – UKMonkey Sep 19 '17 at 13:11