Back to index

openldap  2.4.31
lock.c
Go to the documentation of this file.
00001 /* lock.c - routines to open and apply an advisory lock to a file */
00002 /* $OpenLDAP$ */
00003 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
00004  *
00005  * Copyright 1998-2012 The OpenLDAP Foundation.
00006  * All rights reserved.
00007  *
00008  * Redistribution and use in source and binary forms, with or without
00009  * modification, are permitted only as authorized by the OpenLDAP
00010  * Public License.
00011  *
00012  * A copy of this license is available in the file LICENSE in the
00013  * top-level directory of the distribution or, alternatively, at
00014  * <http://www.OpenLDAP.org/license.html>.
00015  */
00016 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
00017  * All rights reserved.
00018  *
00019  * Redistribution and use in source and binary forms are permitted
00020  * provided that this notice is preserved and that due credit is given
00021  * to the University of Michigan at Ann Arbor. The name of the University
00022  * may not be used to endorse or promote products derived from this
00023  * software without specific prior written permission. This software
00024  * is provided ``as is'' without express or implied warranty.
00025  */
00026 
00027 #include "portable.h"
00028 
00029 #include <stdio.h>
00030 
00031 #include <ac/string.h>
00032 #include <ac/socket.h>
00033 #include <ac/time.h>
00034 #include <ac/unistd.h>
00035 
00036 #ifdef HAVE_SYS_FILE_H
00037 #include <sys/file.h>
00038 #endif
00039 
00040 #include "slap.h"
00041 #include <lutil.h>
00042 
00043 FILE *
00044 lock_fopen( const char *fname, const char *type, FILE **lfp )
00045 {
00046        FILE   *fp;
00047        char   buf[MAXPATHLEN];
00048 
00049        /* open the lock file */
00050        snprintf( buf, sizeof buf, "%s.lock", fname );
00051 
00052        if ( (*lfp = fopen( buf, "w" )) == NULL ) {
00053               Debug( LDAP_DEBUG_ANY, "could not open \"%s\"\n", buf, 0, 0 );
00054 
00055               return( NULL );
00056        }
00057 
00058        /* acquire the lock */
00059        ldap_lockf( fileno(*lfp) );
00060 
00061        /* open the log file */
00062        if ( (fp = fopen( fname, type )) == NULL ) {
00063               Debug( LDAP_DEBUG_ANY, "could not open \"%s\"\n", fname, 0, 0 );
00064 
00065               ldap_unlockf( fileno(*lfp) );
00066               fclose( *lfp );
00067               *lfp = NULL;
00068               return( NULL );
00069        }
00070 
00071        return( fp );
00072 }
00073 
00074 int
00075 lock_fclose( FILE *fp, FILE *lfp )
00076 {
00077        int rc = fclose( fp );
00078        /* unlock */
00079        ldap_unlockf( fileno(lfp) );
00080        fclose( lfp );
00081 
00082        return( rc );
00083 }