Thread: Create Mutex

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    3

    Create Mutex

    Under win32 I could create a mutex to check if there was already an instance of an application running. What's the recommended way to do the same check under linux/bsd? Should I create a mutex with <pthreads.h>?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Here's one technique
    http://lists.wxwidgets.org/archive/w.../msg20443.html
    It would work on windows as well (as a bonus)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Catch with that technique is, if another program uses the same socket, that you may get unintended interactions between it and your program. Of course, the odds of that are low. It is reasonably unlikely that two programs will use the same socket. Then the problem to be considered is that of how both programs respond to data they receive over the socket (eg you send data down that happens to trigger a response you didn't intend from the other program).

  4. #4
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    I also have the same CreateMutex problem. Here's a possible solution using shared memory that I haven't implemented yet.

    Code:
     key = 5678;
         if ((shmid = shmget(key, 27, IPC_CREAT | IPC_EXCL | 0666)) < 0) {
    	  /* Create failed */
    	  /* Read shared memory to determine if another app is running */
    	  /* If the app is running, then exit else fire up */
         
        }
    A scenario would be that the first program (progam A) would initially create the shared memory and post a message to the shared memory indicating that it is running. Now the second program (program b) tries to create the shared memory but it fails because of IPC_EXCL. Program B will now read the shared memory to determine if another instance is running. If another instance is running, then program B will terminate. Otherwise, program B will post a message to shared memory indicating that it is running and will start executing since program A on termination, has already posted a message to shared memory indicating that it is no longer running .

    Thus, a second instance cannot execute until shared memory indicates that it is OK to run.

    Anybody have any suggestions, comments etc?
    Last edited by BobS0327; 12-09-2006 at 07:45 PM.

  5. #5
    Registered User
    Join Date
    Nov 2006
    Posts
    176
    I was always under the impression that a mutex was a binary semaphore. So either having value 0 or 1. I donno where this shared memory stuff is commin from. If this is the case sem.h would be what you wanna look at

  6. #6
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    In a Windows environment, we would use the following code to prevent a second instance of an app from executing while the first instance is still running. In other words, the end user cannot have the same app running two or more times simultaneously. I'm trying to determine the Linux equivalent of the following code:

    Code:
    // Generated this GUID using Guidgen to eliminate multiple instances of fidoh.
    #define UNIQUE "fidoh-{0xc1bde1e, 0xffc1, 0x4cde, 0x9f, 0x45, 0xfe, 0x6e, 0x5f, 0x4d, 0xc, 0x24)"
    HANDLE hMutex;
    
     hMutex = CreateMutex(NULL,TRUE, UNIQUE);
        // Check to determine if we're already running
        if(GetLastError() == ERROR_ALREADY_EXISTS) 
        {
            MessageBox(NULL, "   Application is already running!!!   ",MESSAGE_BOX_TITLE,MB_OK | MB_ICONEXCLAMATION);
            return FALSE;
        }

  7. #7
    Registered User
    Join Date
    Nov 2006
    Posts
    176
    so create a binary semaphore with a prechosen ID, so when the program starts it "attaches" (for lack of a better word) to that semaphore. if the semaphore value is 1 (which it is initialized as), the program decreases the value to 0. if its not 1, the program can go no further so you know another instance must be open, and has already decremented the value of the semaphore.

    ::edit - and also when the program is done executing it has to increase the semaphore value back to 1

  8. #8
    Registered User
    Join Date
    Nov 2006
    Posts
    176
    linux example of only allowing 1 instance of a program:

    initialization program
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/sem.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    
    #define SEMID 313131    /* remember this value, you'll need it later */
    
    union semun {
            int val;
            struct semid_ds *buf;
            unsigned short  *array;
    };
    
    int main(void)
    {
            int sem_set_id, ret_val;
            union semun sem_val;
            struct sembuf sem_op;
    
            sem_val.val = 1;      /* initialization value */
    
            /* create the semaphore with the specified ID */
            sem_set_id = semget(SEMID, 1, IPC_CREAT | 0666);
            if (sem_set_id == -1)
            {
                    perror("semget");
                    exit(1);
            }
    
            /* initialize semaphore */
            ret_val = semctl(sem_set_id, 0, SETVAL, sem_val);
            if (ret_val == -1)
            {
                    perror("semctl");
                    exit(1);
            }
    
            return 0;
    }
    now the main program
    Code:
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <unistd.h>
    
    #define SEMID 313131           /* notice same ID */
    
    int main(void)
    {
            int sem_set_id, ret_val;
            struct sembuf sem_op;
            char ch;
    
            /* attach to semaphore */
            sem_set_id = semget(SEMID, 1, 0666);
            if (sem_set_id == -1)
            {
                    perror("semget");
                    exit(1);
            }
    
            /* check if semaphore is < 1 */
            sem_op.sem_num = 0;
            sem_op.sem_op = -1;
            sem_op.sem_flg = IPC_NOWAIT;    /* don't wait if in use */
    
            if (semop(sem_set_id, &sem_op, 1) == -1)
            {
                    fprintf(stderr, "Sorry, only 1 instance of program allowed\n");
                    exit(1);
            }
    
            /* we're here there must be no other instance running */
            printf("No other instance running\n");
            while (1)
            {
                    ch = getchar();
                    if (ch == 'x') break;
            }
    
            /* increase value back to 1 */
            sem_op.sem_num = 0;
            sem_op.sem_op = 1;
            sem_op.sem_flg = 0;
            semop(sem_set_id, &sem_op, 1);
    
            return 0;
    }
    output:

    ./init_program
    ./main
    No other instance running

    goto another terminal
    ./main
    Sorry, only 1 instance of program allowed

    go back to other terminal
    type x hit enter
    program exits

    go back to other terminal once more
    ./main
    No other instance running
    x
    Last edited by sl4nted; 12-09-2006 at 09:52 PM.

  9. #9
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    It's exactly what I need.

    THANX!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can't create child windows
    By OnionKnight in forum Windows Programming
    Replies: 4
    Last Post: 04-10-2011, 04:13 PM
  2. WM_COPYDATA and mutex selecting multiple files
    By gh0st in forum Windows Programming
    Replies: 2
    Last Post: 10-27-2006, 02:22 PM
  3. Threading and mutex's
    By megatron09 in forum C++ Programming
    Replies: 14
    Last Post: 09-07-2006, 02:40 PM
  4. Create a file from c++ program
    By Dan17 in forum C++ Programming
    Replies: 2
    Last Post: 05-08-2006, 04:25 PM
  5. How to Create reference to an array in C++
    By shiv_tech_quest in forum C++ Programming
    Replies: 2
    Last Post: 12-20-2002, 10:01 AM