Mutex in shared memory when one user crashes?

后端 未结 5 2053
甜味超标
甜味超标 2020-12-29 08:05

Suppose that a process is creating a mutex in shared memory and locking it and dumps core while the mutex is locked.

Now in another process how do I detect that mute

5条回答
  •  悲哀的现实
    2020-12-29 08:36

    How about file-based locking (using flock(2))? These are automatically released when the process holding it dies.

    Demo program:

    #include 
    #include 
    #include 
    
    void main() {
      FILE * f = fopen("testfile", "w+");
    
      printf("pid=%u time=%u Getting lock\n", getpid(), time(NULL));
      flock(fileno(f), LOCK_EX);
      printf("pid=%u time=%u Got lock\n", getpid(), time(NULL));
    
      sleep(5);
      printf("pid=%u time=%u Crashing\n", getpid(), time(NULL));
      *(int *)NULL = 1;
    }
    

    Output (I've truncated the PIDs and times a bit for clarity):

    $ ./a.out & sleep 2 ; ./a.out 
    [1] 15
    pid=15 time=137 Getting lock
    pid=15 time=137 Got lock
    pid=17 time=139 Getting lock
    pid=15 time=142 Crashing
    pid=17 time=142 Got lock
    pid=17 time=147 Crashing
    [1]+  Segmentation fault      ./a.out
    Segmentation fault
    

    What happens is that the first program acquires the lock and starts to sleep for 5 seconds. After 2 seconds, a second instance of the program is started which blocks while trying to acquire the lock. 3 seconds later, the first program segfaults (bash doesn't tell you this until later though) and immediately, the second program gets the lock and continues.

提交回复
热议问题