safelock.c
/* Atomically create and open a file with a unique filename
 *
 * mkstemp_mode allows the mode to be specifed, unlike mkstemp. */
Atomically create and open a file with a unique filename
mkstemp_mode allows the mode to be specifed, unlike mkstemp.
Atomically create and open a file with a unique filename mkstemp_mode allows the mode to be specifed unlike mkstemp .
static int mkstemp_mode(char *filename, mode_t mode)
{
    unsigned short seed[3];
    int fd, try, prefix_len;
    char *suffix;
    assert(filename);
    seed_init(seed);
    prefix_len = strlen(filename) - 6;
    suffix = &filename[prefix_len];
    if (prefix_len < 0 || strcmp(suffix, "XXXXXX")) {
        errno = EINVAL;
        return -1;
    }
    try = 1;
    do {
        sprintf(suffix, "%06x", (unsigned)nrand48(seed) & 0xFFFFFF);
        fd = open(filename, O_CREAT|O_EXCL|O_RDWR, mode);
    } while (fd < 0 && errno == EEXIST && try++ < 10);
    return fd;
}
static int mkstemp_mode ( char * filename , mode_t mode ) { unsigned short seed [ 3 ] ; int fd , try , prefix_len ; char * suffix ; assert ( filename ) ; seed_init ( seed ) ; prefix_len = strlen ( filename ) - 6 ; suffix = & filename [ prefix_len ] ; if ( prefix_len < 0 || strcmp ( suffix , " " ) ) { errno = EINVAL ; return -1 ; } try = 1 ; do { sprintf ( suffix , " " , ( unsigned ) nrand48 ( seed ) & 0xFFFFFF ) ; fd = open ( filename , O_CREAT | O_EXCL | O_RDWR , mode ) ; } while ( fd < 0 && errno == EEXIST && try ++ < 10 ) ; return fd ; }
Atomically create and open a file with a unique filename
 mkstemp_mode allows the mode to be specifed, unlike mkstemp.
Atomically create and open a file with a unique filename mkstemp_mode allows the mode to be specifed unlike mkstemp .
/* Calculate suffix pointer and ensure suffix is XXXXXX */