Advertisement
Fiolek

Single app instance with semaphores

Jun 13th, 2015
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.63 KB | None | 0 0
  1. // Link with pthread support - gcc -pthread -o A A.c
  2. #include <errno.h>
  3. #include <fcntl.h>
  4. #include <sys/stat.h>
  5. #include <semaphore.h>
  6. #include <stdio.h>
  7.  
  8. #define SEM_NAME "/sample_app_semaphore"
  9.  
  10. int main()
  11. {
  12.     sem_t *sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0666, 0);
  13.     if (sem == SEM_FAILED)
  14.     {
  15.         if (errno == EEXIST)
  16.         {
  17.             puts("This application is already running.");
  18.             return 1;
  19.         }
  20.         puts("Cannot create semaphore - it may already exist");
  21.         return 2;
  22.     }
  23.  
  24.     puts("Press any key...");
  25.     getchar();
  26.  
  27.     sem_close(sem);
  28.     sem_unlink(SEM_NAME);
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement