Skip to content

Instantly share code, notes, and snippets.

@yamnikov-oleg
Last active August 6, 2025 12:48
Show Gist options
  • Select an option

  • Save yamnikov-oleg/abf61cf96b4867cbf72d to your computer and use it in GitHub Desktop.

Select an option

Save yamnikov-oleg/abf61cf96b4867cbf72d to your computer and use it in GitHub Desktop.

Revisions

  1. yamnikov-oleg revised this gist Apr 5, 2018. 1 changed file with 21 additions and 0 deletions.
    21 changes: 21 additions & 0 deletions LICENSE
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    MIT License

    Copyright (c) 2018 Oleg Yamnikov

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
  2. yamnikov-oleg revised this gist Feb 22, 2016. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions shared_mutex.c
    Original file line number Diff line number Diff line change
    @@ -11,6 +11,7 @@

    shared_mutex_t shared_mutex_init(char *name) {
    shared_mutex_t mutex = {NULL, 0, NULL, 0};
    errno = 0;

    // Open existing shared memory object, or create one.
    // Two separate calls are needed here, to mark fact of creation
  3. yamnikov-oleg revised this gist Feb 21, 2016. 3 changed files with 20 additions and 7 deletions.
    9 changes: 9 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -17,6 +17,10 @@ int main() {
    return 1;
    }

    if (mutex.created) {
    printf("The mutex was just created\n");
    }

    // Use pthread calls for locking and unlocking.
    pthread_mutex_lock(mutex.ptr);
    printf("Press eny key to unlock the mutex");
    @@ -57,6 +61,11 @@ typedef struct shared_mutex_t {
    int shm_fd; // Descriptor of shared memory object.
    char* name; // Name of the mutex and associated
    // shared memory object.
    int created; // Equals 1 (true) if initialization
    // of this structure caused creation
    // of a new shared mutex.
    // Equals 0 (false) if this mutex was
    // just retrieved from shared memory.
    } shared_mutex_t;
    ```

    9 changes: 4 additions & 5 deletions shared_mutex.c
    Original file line number Diff line number Diff line change
    @@ -10,16 +10,15 @@
    #include <string.h> // strcpy

    shared_mutex_t shared_mutex_init(char *name) {
    shared_mutex_t mutex = {NULL, 0};
    int created = 0;
    shared_mutex_t mutex = {NULL, 0, NULL, 0};

    // Open existing shared memory object, or create one.
    // Two separate calls are needed here, to mark fact of creation
    // for later initialization of pthread mutex.
    mutex.shm_fd = shm_open(name, O_RDWR, 0660);
    if (errno == ENOENT) {
    mutex.shm_fd = shm_open(name, O_RDWR|O_CREAT, 0660);
    created = 1;
    mutex.created = 1;
    }
    if (mutex.shm_fd == -1) {
    perror("shm_open");
    @@ -50,7 +49,7 @@ shared_mutex_t shared_mutex_init(char *name) {

    // If shared memory was just initialized -
    // initialize the mutex as well.
    if (created) {
    if (mutex.created) {
    pthread_mutexattr_t attr;
    if (pthread_mutexattr_init(&attr)) {
    perror("pthread_mutexattr_init");
    @@ -87,7 +86,7 @@ int shared_mutex_close(shared_mutex_t mutex) {
    }

    int shared_mutex_destroy(shared_mutex_t mutex) {
    if (pthread_mutex_destroy(mutex.ptr)) {
    if ((errno = pthread_mutex_destroy(mutex.ptr))) {
    perror("pthread_mutex_destroy");
    return -1;
    }
    9 changes: 7 additions & 2 deletions shared_mutex.h
    Original file line number Diff line number Diff line change
    @@ -11,8 +11,13 @@ typedef struct shared_mutex_t {
    pthread_mutex_t *ptr; // Pointer to the pthread mutex and
    // shared memory segment.
    int shm_fd; // Descriptor of shared memory object.
    char* name; // Name the mutex and associated
    char* name; // Name of the mutex and associated
    // shared memory object.
    int created; // Equals 1 (true) if initialization
    // of this structure caused creation
    // of a new shared mutex.
    // Equals 0 (false) if this mutex was
    // just retrieved from shared memory.
    } shared_mutex_t;

    // Initialize a new shared mutex with given `name`. If a mutex
    @@ -58,4 +63,4 @@ int shared_mutex_close(shared_mutex_t mutex);
    // **NOTE:** It will not unlock locked mutex.
    int shared_mutex_destroy(shared_mutex_t mutex);

    #endif // SHARED_MUTEX_H
    #endif // SHARED_MUTEX_H
  4. yamnikov-oleg created this gist Feb 21, 2016.
    99 changes: 99 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,99 @@
    # shared_mutex

    Microlibrary for inter-process mutexes on Linux.

    ## Example which says it all

    ```c
    #include "shared_mutex.h"
    #include <stdio.h>

    int main() {
    // Init shared mutex by a name, which can be used by
    // any other process to access the mutex.
    // This function both creates new and opens an existing mutex.
    shared_mutex_t mutex = shared_mutex_init("/my-mutex");
    if (mutex.ptr == NULL) {
    return 1;
    }

    // Use pthread calls for locking and unlocking.
    pthread_mutex_lock(mutex.ptr);
    printf("Press eny key to unlock the mutex");
    getchar();
    pthread_mutex_unlock(mutex.ptr);

    // Closing is used to release local resources, used by a mutex.
    // It's still available to any other process.
    if (shared_mutex_close(mutex)) {
    return 1;
    }
    return 0;
    }

    int cleanup() {
    // Mutex destruction completely cleans it from system memory.
    if (shared_mutex_destroy(mutex)) {
    return 1;
    }
    return 0;
    }
    ```

    ## Usage

    * Download `shared_mutex.h` and `shared_mutex.c` into your project.
    * Building requires linking with `pthread` and `librt`.

    ## Docs

    ### shared_mutex_t

    Structure of a shared mutex.
    ```c
    typedef struct shared_mutex_t {
    pthread_mutex_t *ptr; // Pointer to the pthread mutex and
    // shared memory segment.
    int shm_fd; // Descriptor of shared memory object.
    char* name; // Name of the mutex and associated
    // shared memory object.
    } shared_mutex_t;
    ```

    ### shared_mutex_init

    ```c
    shared_mutex_t shared_mutex_init(char *name);
    ```
    Initialize a new shared mutex with given `name`. If a mutex with such name exists in the system, it will be loaded. Otherwise a new mutes will by created.
    In case of any error, it will be printed into the standard output and the returned structure will have `ptr` equal `NULL`. `errno` wil not be reset in such case, so you may used it.
    **NOTE:** In case when the mutex appears to be uncreated, this function becomes *non-thread-safe*. If multiple threads call it at one moment, there occur several race conditions, in which one call might recreate another's shared memory object or rewrite another's pthread mutex in the shared memory. There is no workaround currently, except to run first initialization only before multi-threaded or multi-process functionality.
    ### shared_mutex_close
    ```c
    int shared_mutex_close(shared_mutex_t mutex);
    ```

    Close access to the shared mutex and free all the resources, used by the structure.

    Returns 0 in case of success. If any error occurs, it will be printed into the standard output and the function will return -1. `errno` wil not be reset in such case, so you may used it.

    **NOTE:** It will not destroy the mutex. The mutex would not only be available to other processes using it right now, but also to any process which might want to use it later on. For complete desctruction use `shared_mutex_destroy` instead.

    **NOTE:** It will not unlock locked mutex.

    ### shared_mutex_destroy

    ```c
    int shared_mutex_destroy(shared_mutex_t mutex);
    ```
    Close and destroy shared mutex. Any open pointers to it will be invalidated.
    Returns 0 in case of success. If any error occurs, it will be printed into the standard output and the function will return -1. `errno` wil not be reset in such case, so you may used it.
    **NOTE:** It will not unlock locked mutex.
    110 changes: 110 additions & 0 deletions shared_mutex.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,110 @@
    #include "shared_mutex.h"
    #include <errno.h> // errno, ENOENT
    #include <fcntl.h> // O_RDWR, O_CREATE
    #include <linux/limits.h> // NAME_MAX
    #include <sys/mman.h> // shm_open, shm_unlink, mmap, munmap,
    // PROT_READ, PROT_WRITE, MAP_SHARED, MAP_FAILED
    #include <unistd.h> // ftruncate, close
    #include <stdio.h> // perror
    #include <stdlib.h> // malloc, free
    #include <string.h> // strcpy

    shared_mutex_t shared_mutex_init(char *name) {
    shared_mutex_t mutex = {NULL, 0};
    int created = 0;

    // Open existing shared memory object, or create one.
    // Two separate calls are needed here, to mark fact of creation
    // for later initialization of pthread mutex.
    mutex.shm_fd = shm_open(name, O_RDWR, 0660);
    if (errno == ENOENT) {
    mutex.shm_fd = shm_open(name, O_RDWR|O_CREAT, 0660);
    created = 1;
    }
    if (mutex.shm_fd == -1) {
    perror("shm_open");
    return mutex;
    }

    // Truncate shared memory segment so it would contain
    // pthread_mutex_t.
    if (ftruncate(mutex.shm_fd, sizeof(pthread_mutex_t)) != 0) {
    perror("ftruncate");
    return mutex;
    }

    // Map pthread mutex into the shared memory.
    void *addr = mmap(
    NULL,
    sizeof(pthread_mutex_t),
    PROT_READ|PROT_WRITE,
    MAP_SHARED,
    mutex.shm_fd,
    0
    );
    if (addr == MAP_FAILED) {
    perror("mmap");
    return mutex;
    }
    pthread_mutex_t *mutex_ptr = (pthread_mutex_t *)addr;

    // If shared memory was just initialized -
    // initialize the mutex as well.
    if (created) {
    pthread_mutexattr_t attr;
    if (pthread_mutexattr_init(&attr)) {
    perror("pthread_mutexattr_init");
    return mutex;
    }
    if (pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)) {
    perror("pthread_mutexattr_setpshared");
    return mutex;
    }
    if (pthread_mutex_init(mutex_ptr, &attr)) {
    perror("pthread_mutex_init");
    return mutex;
    }
    }
    mutex.ptr = mutex_ptr;
    mutex.name = (char *)malloc(NAME_MAX+1);
    strcpy(mutex.name, name);
    return mutex;
    }

    int shared_mutex_close(shared_mutex_t mutex) {
    if (munmap((void *)mutex.ptr, sizeof(pthread_mutex_t))) {
    perror("munmap");
    return -1;
    }
    mutex.ptr = NULL;
    if (close(mutex.shm_fd)) {
    perror("close");
    return -1;
    }
    mutex.shm_fd = 0;
    free(mutex.name);
    return 0;
    }

    int shared_mutex_destroy(shared_mutex_t mutex) {
    if (pthread_mutex_destroy(mutex.ptr)) {
    perror("pthread_mutex_destroy");
    return -1;
    }
    if (munmap((void *)mutex.ptr, sizeof(pthread_mutex_t))) {
    perror("munmap");
    return -1;
    }
    mutex.ptr = NULL;
    if (close(mutex.shm_fd)) {
    perror("close");
    return -1;
    }
    mutex.shm_fd = 0;
    if (shm_unlink(mutex.name)) {
    perror("shm_unlink");
    return -1;
    }
    free(mutex.name);
    return 0;
    }
    61 changes: 61 additions & 0 deletions shared_mutex.h
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    #ifndef SHARED_MUTEX_H
    #define SHARED_MUTEX_H

    #define _BSD_SOURCE // for ftruncate
    #include <pthread.h> // pthread_mutex_t, pthread_mutexattr_t,
    // pthread_mutexattr_init, pthread_mutexattr_setpshared,
    // pthread_mutex_init, pthread_mutex_destroy

    // Structure of a shared mutex.
    typedef struct shared_mutex_t {
    pthread_mutex_t *ptr; // Pointer to the pthread mutex and
    // shared memory segment.
    int shm_fd; // Descriptor of shared memory object.
    char* name; // Name the mutex and associated
    // shared memory object.
    } shared_mutex_t;

    // Initialize a new shared mutex with given `name`. If a mutex
    // with such name exists in the system, it will be loaded.
    // Otherwise a new mutes will by created.
    //
    // In case of any error, it will be printed into the standard output
    // and the returned structure will have `ptr` equal `NULL`.
    // `errno` wil not be reset in such case, so you may used it.
    //
    // **NOTE:** In case when the mutex appears to be uncreated,
    // this function becomes *non-thread-safe*. If multiple threads
    // call it at one moment, there occur several race conditions,
    // in which one call might recreate another's shared memory
    // object or rewrite another's pthread mutex in the shared memory.
    // There is no workaround currently, except to run first
    // initialization only before multi-threaded or multi-process
    // functionality.
    shared_mutex_t shared_mutex_init(char *name);

    // Close access to the shared mutex and free all the resources,
    // used by the structure.
    //
    // Returns 0 in case of success. If any error occurs, it will be
    // printed into the standard output and the function will return -1.
    // `errno` wil not be reset in such case, so you may used it.
    //
    // **NOTE:** It will not destroy the mutex. The mutex would not
    // only be available to other processes using it right now,
    // but also to any process which might want to use it later on.
    // For complete desctruction use `shared_mutex_destroy` instead.
    //
    // **NOTE:** It will not unlock locked mutex.
    int shared_mutex_close(shared_mutex_t mutex);

    // Close and destroy shared mutex.
    // Any open pointers to it will be invalidated.
    //
    // Returns 0 in case of success. If any error occurs, it will be
    // printed into the standard output and the function will return -1.
    // `errno` wil not be reset in such case, so you may used it.
    //
    // **NOTE:** It will not unlock locked mutex.
    int shared_mutex_destroy(shared_mutex_t mutex);

    #endif // SHARED_MUTEX_H