Using Mutex to prevent reentry

  • 為了防止設備或是process被重複開啟, 可以用Mutex鎖定設備或是process.

  • 當process結束或是主動釋放Mutex, 才可以讓其他process再度進入該程式碼中.

  • 利用判斷Mutex來判斷設備或是process是否已被開啟也可以達到保護不被reentry.

  • example: 鎖定特定的port:

    • 1.在開port時加入:

       char mutexName[20];
       sprintf(mutexName,"mutex%d",port);
      
       *hMutex = CreateMutexA(NULL, TRUE, mutexName);
       //printf("%d\n", *hMutex );
       if (*hMutex == NULL) {
         //printf("Error creating mutex.\n");
          return 0;
       }
       if (GetLastError() == ERROR_ALREADY_EXISTS) {
        //printf("The mutex alread exists.\n");
         return 0;
       }
    • 2.在關port時加入:

       ReleaseMutex(hMutex); 
       CloseHandle(hMutex);

Last updated

Was this helpful?