1 /* $NetBSD: lock.c,v 1.1.1.3 2010/12/12 15:22:32 adam Exp $ */ 2 3 /* lock.c - routines to open and apply an advisory lock to a file */ 4 /* OpenLDAP: pkg/ldap/servers/slapd/lock.c,v 1.32.2.5 2010/04/13 20:23:16 kurt Exp */ 5 /* This work is part of OpenLDAP Software <http://www.openldap.org/>. 6 * 7 * Copyright 1998-2010 The OpenLDAP Foundation. 8 * All rights reserved. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted only as authorized by the OpenLDAP 12 * Public License. 13 * 14 * A copy of this license is available in the file LICENSE in the 15 * top-level directory of the distribution or, alternatively, at 16 * <http://www.OpenLDAP.org/license.html>. 17 */ 18 /* Portions Copyright (c) 1995 Regents of the University of Michigan. 19 * All rights reserved. 20 * 21 * Redistribution and use in source and binary forms are permitted 22 * provided that this notice is preserved and that due credit is given 23 * to the University of Michigan at Ann Arbor. The name of the University 24 * may not be used to endorse or promote products derived from this 25 * software without specific prior written permission. This software 26 * is provided ``as is'' without express or implied warranty. 27 */ 28 29 #include "portable.h" 30 31 #include <stdio.h> 32 33 #include <ac/string.h> 34 #include <ac/socket.h> 35 #include <ac/time.h> 36 #include <ac/unistd.h> 37 38 #ifdef HAVE_SYS_FILE_H 39 #include <sys/file.h> 40 #endif 41 42 #include "slap.h" 43 #include <lutil.h> 44 45 FILE * 46 lock_fopen( const char *fname, const char *type, FILE **lfp ) 47 { 48 FILE *fp; 49 char buf[MAXPATHLEN]; 50 51 /* open the lock file */ 52 snprintf( buf, sizeof buf, "%s.lock", fname ); 53 54 if ( (*lfp = fopen( buf, "w" )) == NULL ) { 55 Debug( LDAP_DEBUG_ANY, "could not open \"%s\"\n", buf, 0, 0 ); 56 57 return( NULL ); 58 } 59 60 /* acquire the lock */ 61 ldap_lockf( fileno(*lfp) ); 62 63 /* open the log file */ 64 if ( (fp = fopen( fname, type )) == NULL ) { 65 Debug( LDAP_DEBUG_ANY, "could not open \"%s\"\n", fname, 0, 0 ); 66 67 ldap_unlockf( fileno(*lfp) ); 68 fclose( *lfp ); 69 *lfp = NULL; 70 return( NULL ); 71 } 72 73 return( fp ); 74 } 75 76 int 77 lock_fclose( FILE *fp, FILE *lfp ) 78 { 79 int rc = fclose( fp ); 80 /* unlock */ 81 ldap_unlockf( fileno(lfp) ); 82 fclose( lfp ); 83 84 return( rc ); 85 } 86