J. Doe
J. Doe

Reputation: 125

How do you block shared memory access until it is ready?

I'm trying to share a mutex between several processes. Each process will begin running at some random time so I need each to to be capable of setting up the shared memory and getting the mutex ready for usage. This works great so far:

int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR);
if (fd < 0) {
    fd = shm_open(name, O_RDWR, S_IRUSR);
} else {
    //**critical section**

    // set up the mutex inside the shared memory
    // update permissions so other processes can access the shared memory
    fchmod(fd, S_IRUSR | S_IWUSR)

    //**critical section**
}

// mmap() shared memory
// pthread_mutex_lock()
// some other critical section
// pthread mutex unlock()

but if I add a sleep() right at the start of the else block to simulate slow creation of the shared memory I run into a problem where another process will see the created file and try to use it right away, before it's ready.

Is there any way to block the shm_open() call until the shared memory is ready? like telling it to wait until it has sufficient permissions to open the file (the last step of my critical section). Or is there some way to lock the file immediately on creation so that other processes must wait for it to be set up and unlocked, flock()?

Upvotes: 0

Views: 1056

Answers (1)

J. Doe
J. Doe

Reputation: 125

I've actually solved my own question here, anyone have any suggestions for improvements?

Solution:

int lock_fd shm_open(setup_control, O_RDWR | O_CREAT, S_IRUSR, S_IWUSR);
flock(lock_fd, LOCK_EX);

int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR, S_IWUSR);
if (fd < 0) {
    fd = shm_open(name, O_RDWR, S_IRUSR);
} else {
    //**critical section**

    // set up the mutex inside the shared memory

    //**critical section**
}
flock(lock_fd, LOCK_UN);

// mmap() shared memory
// pthread_mutex_lock()
// some other critical section
// pthread mutex unlock()

Basically the locking file ensures that only 1 process can be acquiring or setting up the mutex at once which means by the time [the next] process is opening the mutex file it has already completed setting up

Upvotes: 2

Related Questions