I want ensure the application is not launched twice on the same computer but I failed.
My task is to port our application from Windows to UNIX-like systems. At least to Alt-Linux (uname -srvoi shows:
Linux 2.6.32-el-smp-alt27 #1 SMP Tue Sep 20 19:35:51 UTC 2011 unknown GNU/Linux). I'am not familiar with Linux-es before, hence send my question to this sub-forum for noobs.
For Windows I just create file in write mode and with ban for writing for other applications. On application exit I close the file and delete it. If application crushed or forcibly terminated it is OK because file stay existing but system allows to me to create it again.
For Alt-Linux I already tried:
1) 'fopen' file and 'lockf' it
- result: F_TEST hangs second instance of application instead immediately return with error. Probably it is beacuse file system is nfs and cannot lock files. (No, I cannot select other file system. App should work on nfs too.)
2) 'fopen' file and 'flock' it
- result: the same
3) 'open' file with O_CREATE|O_EXCL flags (mode is 0666)
- result: OK until I forcibly terminates first instance. As result file stay on disk and I cannot start application again
4) 'unlink' file and immediately 'open' it with O_CREATE|O_EXCL
- result: just does not work. I can start second instance (yes, I know in UNIX 'unlink' removes file only from directory but keep on disk until first instance closed file handle)
5) Use 'shm_open' with O_CREATE|O_EXCL flags
- result: as in 3)
6) Use 'shm_unlink' + 'shm_open' with O_CREATE|O_EXCL flags
- result: as in 4)
7), 8) Use 'sem_open' with O_CREATE|O_EXCL flags with or without sem_unlink before
- result: as in 3), 4)
10) Use 'sem_open' with O_CREATE, without O_EXCL but use 'sem_trywait' after
- result: OK until I forcibly terminates first instance. As result semaphore stay with value 0 and application cannot start again. I can delete semaphore but I do not know how to distinguish situations:
- semaphore is 0 because application is already running
- semaphore is 0 because application crushed
Below sample code:
Code:
int main()
{
sem_t *sem= sem_open("/a.out.sem", O_CREAT, 0666, 1);
if (sem != SEM_FAILED)
{
printf("success\n");
if (0 == sem_trywait(sem))
printf("trywait ok\n");
else
printf("cannot trywait\n");
}
else
printf("failure\n");
for(;;)
{
sleep(1);
}
return 0;
}
Start application and abort it with ^C to imit situation of application is killed before can call sem_post and/or sem_unlink.
What can I do?