How do I recover a semaphore when the process that decremented it to zero crashes?

后端 未结 8 531
轻奢々
轻奢々 2020-12-02 13:23

I have multiple apps compiled with g++, running in Ubuntu. I\'m using named semaphores to co-ordinate between different processes.

All works fine except in

相关标签:
8条回答
  • 2020-12-02 13:51

    Simply do a sem_unlink() immediately after the sem_open(). Linux will remove after all processes have closed the resource, which includes internal closes.

    0 讨论(0)
  • Use a lock file instead of a semaphore, much like @Stéphane's solution but without the flock() calls. You can simply open the file using an exclusive lock:

    //call to open() will block until it can obtain an exclusive lock on the file.
    errno = 0;
    int fd = open("/tmp/.lockfile", 
        O_CREAT | //create the file if it's not present.
        O_WRONLY | //only need write access for the internal locking semantics.
        O_EXLOCK, //use an exclusive lock when opening the file.
        S_IRUSR | S_IWUSR); //permissions on the file, 600 here.
    
    if (fd == -1) {
        perror("open() failed");
        exit(EXIT_FAILURE);
    }
    
    printf("Entered critical section.\n);
    //Do "critical" stuff here.
    
    //exit the critical section
    errno = 0;
    if (close(fd) == -1) {
        perror("close() failed");
        exit(EXIT_FAILURE);
    }
    
    printf("Exited critical section.\n");
    
    0 讨论(0)
提交回复
热议问题