safelock.c
/* Initialise a safelock_t object for a lock file.
 *
 * Create the lock file if necessary (provided mode is non-zero).
 * safelock_t is returned in an unlocked state.
 *
 * Returns 0 on success, otherwise errno
 */
Initialise a safelock_t object for a lock file.
Create the lock file if necessary (provided mode is non-zero).
safelock_t is returned in an unlocked state.

Returns 0 on success, otherwise errno
Initialise a safelock_t object for a lock file . Create the lock file if necessary ( provided mode is non - zero ) . safelock_t is returned in an unlocked state . Returns 0 on success otherwise errno
int safelock_open(safelock_t *lock, const char *filename, mode_t mode)
{
    lock_data_t *shared;
    int fd;
    safelock_t newlock;
    int err;
    fd = open(filename, O_RDWR);
    if (fd < 0 && errno == ENOENT && mode) {
            err = safelock_create(filename, mode);
            if (err)
                return err;
            fd = open(filename, O_RDWR);
    }
    if (fd < 0)
        return errno;
    shared = mmap_lock_data(fd);
    if (!shared) {
        err = errno;
        close(fd);
        return err;
    }
    newlock = malloc(sizeof(*newlock));
    if (!newlock)
        goto error_nomem;
    newlock->filename = strdup(filename);
    if (!newlock->filename) {
        free(newlock);
        goto error_nomem;
    }
    newlock->shared = shared;
    newlock->fd = fd;
    newlock->locked = 0;
    *lock = newlock;
    return 0;
error_nomem:
    munmap_lock_data(shared);
    close(fd);
    return ENOMEM;
}
int safelock_open ( safelock_t * lock , const char * filename , mode_t mode ) { lock_data_t * shared ; int fd ; safelock_t newlock ; int err ; fd = open ( filename , O_RDWR ) ; if ( fd < 0 && errno == ENOENT && mode ) { err = safelock_create ( filename , mode ) ; if ( err ) return err ; fd = open ( filename , O_RDWR ) ; } if ( fd < 0 ) return errno ; shared = mmap_lock_data ( fd ) ; if ( ! shared ) { err = errno ; close ( fd ) ; return err ; } newlock = malloc ( sizeof ( * newlock ) ) ; if ( ! newlock ) goto error_nomem ; newlock -> filename = strdup ( filename ) ; if ( ! newlock -> filename ) { free ( newlock ) ; goto error_nomem ; } newlock -> shared = shared ; newlock -> fd = fd ; newlock -> locked = 0 ; * lock = newlock ; return 0 ; error_nomem : munmap_lock_data ( shared ) ; close ( fd ) ; return ENOMEM ; }
Initialise a safelock_t object for a lock file.
Initialise a safelock_t object for a lock file .
/* The fd may leak if close fails (undefined), but this is
         * the lesser evil.. */